开发者

Get enum name when value is known

I have an enum that has different colors in it. I would like to pass some function an int and have it return the color name that is in the enum in that position.

What's the way开发者_Go百科 to do this?


return ((MyEnumClass)n).ToString();


Another option is to use the GetName static method:

Enum.GetName(typeof(MyEnumClass), n);

This has the benefit that the code speaks for itself. It should be obvious that it returns the name of the enum (which may be a bit difficult to realize when you use for example the ToString method).


In c# 6 you can use nameof.

nameof(YourEnum.Something)

results in:

something


If your enum with colors is named MyColorEnumName, Try

Enum.GetName(typeof(MyColorEnumName),  enumColorValue)


If you care about performance beware of using any of the suggestions given here: they all use reflection to give a string value for the enum. If the string value is what you'll need most, you are better off using strings. If you still want type safety, define a class and a collection to define your "enums", and have the class echo its name in the ToString() override.


Below is the example to get Enum name based on the color value.

  class Program
     {
          //Declare Enum
          enum colors {white=0,black=1,skyblue=2,blue=3 }
      static void Main(string[] args)
        {
          // It will return single color name which is "skyblue"
             string colorName=Enum.GetName(typeof(colors),2);

          //it will returns all the color names in string array.
          //We can retrive either through loop or pass index in array.
             string[] colorsName = Enum.GetNames(typeof(colors));

         //Passing index in array and it would return skyblue color name
             string colName = colorsName[2];

             Console.WriteLine(colorName);
             Console.WriteLine(colName);
             Console.ReadLine();
        }
    }


((YourEnum)Value).ToString()

For eg.

((MyEnum)2).ToString()

Note: Points to remember, your enum should be decorated by [Flag] and enum value must be greater than 0.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜