How to read the Description property of an enumeration value in C #

Source: Internet
Author: User

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 #

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.