📜 ⬆️ ⬇️

“Sets” in C #

Again I am writing about the fact that, in general, it is known =) But if somewhere you need to pass several flags as a function argument, then this method can be used. There are no sets (UPD: not as classes in the .Net library, but as a structure built in the syntax) in C #. But then there is the [FlagsAttribute] attribute for enums (i.e., for enum 's):
[Flags]<br> enum Magic<br>{<br> None = 0,<br><br> Fire = 1, // <br> Air = 2, // <br> Water = 4, // <br> Earth = 8, // <br><br> All = Fire | Air | Water | Earth<br>}<br> <br> * This source code was highlighted with Source Code Highlighter .
Just give an example:
class Program<br>{<br> // <br> [Flags]<br> enum Magic<br> {<br> None = 0,<br><br> Fire = 1, // <br> Air = 2, // <br> Water = 4, // <br> Earth = 8, // <br><br> All = Fire | Air | Water | Earth<br> }<br><br> // , <br> static void CastSpell( float power, Magic source)<br> {<br> if ((source & Magic.All) == Magic.None)<br> {<br> Console .WriteLine( " ." );<br> Console .WriteLine();<br> return ;<br> }<br><br> if ((source & Magic.Fire) != 0)<br> Console .WriteLine( " ." );<br> if ((source & Magic.Air) != 0)<br> Console .WriteLine( " ." );<br> if ((source & Magic.Water) != 0)<br> Console .WriteLine( " ." );<br> if ((source & Magic.Earth) != 0)<br> Console .WriteLine( " ." );<br><br> Console .WriteLine( "--!!! ( {0} )." , power);<br> Console .WriteLine();<br> }<br><br> // <br> static void Main( string [] args)<br> {<br> CastSpell(1, 0);<br> CastSpell(2, Magic.None);<br> CastSpell(3, Magic.Fire);<br> CastSpell(4, Magic.Earth | Magic.Water);<br> CastSpell(5, Magic.Air | Magic.Fire | Magic.Earth);<br> CastSpell(6, Magic.All);<br> }<br>}<br> <br> * This source code was highlighted with Source Code Highlighter .
This, of course, is not a real set, with its crutches, but you can use it. The main thing to remember is that the elements of the set must be powers of two and remember how bit operations work. Well, still worth reading in MSDN about the "FlagsAttribute Class".

')

Source: https://habr.com/ru/post/73177/


All Articles