C# 擴展方法——獲得枚舉的Description


其他擴展方法詳見:https://www.cnblogs.com/zhuanjiao/p/12060937.html

 

/// <summary>
/// 擴展方法,獲得枚舉的Description
/// </summary>
/// <param name="value">枚舉值</param>
/// <param name="nameInstead">當枚舉值沒有定義DescriptionAttribute,是否使用枚舉名代替,默認是使用</param>
/// <returns>枚舉的Description</returns>
public static string GetDescription(this Enum value, Boolean nameInstead = true)
{
    Type type = value.GetType();
    string name = Enum.GetName(type, value);
    if (name == null)
    {
        return null;
    }
 
    FieldInfo field = type.GetField(name);
    DescriptionAttribute attribute = System.Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
 
    if (attribute == null && nameInstead == true)
    {
        return name;
    }
    return attribute?.Description;
}

  隨便整一個枚舉

public enum ModuleType
 {
     /// <summary>
     /// 中國
     /// </summary>
     [Description("中國")]
     ZH = 1,
     /// <summary>
     /// 美國
     /// </summary>
     [Description("美國")]
     MG = 2
 }

  舉例 :var AppId = ModuleType.ZH.GetDescription()  // 得到“中國”


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM