In C #, there are times when we need to read the Description property of an enumeration value, which means that the enumeration value represents what it means. For example, in this article the enumeration value Chinese, we want to know that it represents the meaning of the description ("Chinese").
There are the following enumerations:
| 123456 |
publicenumEnumLanugage{ [System.ComponentModel.Description("中文")] Chinese, English} |
What we are going to get is the explanatory text "Chinese" in Chinese.
| 123456789 |
publicstring GetEnumDescription(Enum enumValue){ stringstr = enumValue.ToString(); System.Reflection.FieldInfo field = enumValue.GetType().GetField(str); object[] objs = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false); if(objs == null|| objs.Length == 0) returnstr; System.ComponentModel.DescriptionAttribute da = (System.ComponentModel.DescriptionAttribute)objs[0]; returnda.Description;} |
Call Getenumdescription (Enumlanguage.chinese) will return "Chinese", if replaced with enumlanguage.english, because there is no definition of Description on the 中文版, The enum name will be returned directly to 中文版.
How to read the Description property of an enumeration value in C #