Cast enum definition name to string
If i have enum like that:
public enum MyEnum
{
Element1 = 1,
Element2,
Element3,
Element4
}
How could i cast MyEnum
to String()
in the code 开发者_运维技巧
I know that i may cast any Enum
value to sting like that MyEnum.Element1.ToString()
, but how I may cast Enum definition/name to string?
I want to do something like that :
MyEnum.ToString()
Depending on your use case I think you may very well be better off using a display name attribute like the example here. The enum string representation often isn't quite what you'd want to display and you'd need to update code in various places if you wanted that string to change.
As @shsmith said, use:
typeof(MyEnum).Name
But unlike he said, don't use:
MyEnum.GetType().Name
Since MyEnum isn't static, and hence can't invoke that method.
You can use GetType()
on a specific element though, like so:
MyEnum.Element1.GetType().Name //=MyEnum
精彩评论