c# - Bitfield enum extension method to return dictionary of included values -


Enums can definitely be confused I'm trying to make an extension method on Enum type which would be considered one and Will return the names of all the bits that match.

  [flag] public enum PlanetsEnum {Mercury = 1, Venus = 2, Earth = 4, Mars = 8, Jupiter = 16, // etc ....}  

I want to create an extension method that returns the dictionary of only selected values ​​if:

planets of planets = planets.nem.mars | PlanetEnum.Venus; // 10 IDZIN tan = neighbor Foreign Language (KeyWeekeeper & Lift; String, int 32 & gt; kvp in dict) {Console.WriteLine (kvp.Key); } / * * Print: * Mars * Venus * /

I hope Mars & amp; Venus has been written on the console, but I'm looking at all the values ​​of Planet Names. Here is my extension method code:

  Public Fixed IDictionary & lt; String, int32 & gt; ToDictionary (this enum calculation) {type type = counting GetType (); Return Enum.GetValues ​​(type) .Cast & amp; Lt; Int32 & gt; (). ToDictionary (Field => Enum.GetName (Type, Field)); }  

Is anyone seeing what I am doing wrong? I know that Enum.GetValues ​​ is returning all the fields of enum type, how can I just return fields of enum example?

Thanks for any help,

Keith

Here's what you are trying to do is the LINQ-ified version. The key you are skipping is checking the current value:

  Public Fixed IDictionary & lt; String, int & gt; ToDictionary (calculate the Enum) {int value = (int) (object) calculation; Return Enum.GetValues ​​(count. GetType ()). OfType & lt; Int & gt; (). Where (v = & gt; (v and amp; value) == value). Coexist (v => Enum.GetName (c. GetType (), V));  

Edit: We calculate the (int) (object), a little bit more on this: Divided:

BTWAR operators only act against integral types (like int) and bullion, but the AE is not directly capable of cast-in, so we must hate any object and assume that this is actually Shows an integer in the form of the underlying type - the compiler gives us an object T will allow you to put an int if the calculation is not an integer-based, so it throws a runtime exception.


Comments

Popular posts from this blog

sql - dynamically varied number of conditions in the 'where' statement using LINQ -

asp.net mvc - Dynamically Generated Ajax.BeginForm -

Debug on symbian -