2022-09-12|閱讀時間 ‧ 約 2 分鐘

取得Enum列舉定義的字串

    新增資料夾 Extension,建立類別
    /// <summary>擴充功能</summary>
    public static class CHelpExtensions
    {
      /// <summary>
      /// 取得列舉定義的字串
      /// </summary>
      /// <param name="value">列舉</param>
      public static string GetDescription(this Enum value)
      {
        FieldInfo fi = value.GetType().GetField(value.ToString());
        DescriptionAttribute[] attributes = fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];

        //若取不到屬性,則取名稱
        return attributes.Length > 0 ? attributes[0].Description : value.ToString();
      }
    }
    分享至
    成為作者繼續創作的動力吧!
    © 2024 vocus All rights reserved.