在寫程式時,多多少少都會寫一些列舉,可以讓程式更加的安全,但有些時候,列舉在變數命名時必須為英文,送到前端時則必須顯示成中文,要怎麼讓中英文產生關連呢?
可以參考以下的作法
建立列舉
using System.ComponentModel;
public enum Status
{
    [Description("上線")]
    OnLine = 10,
}
再為列舉型別寫一個擴充方法,用意在於傳回當前列舉Description內的值
using System;
using System.ComponentModel;
using System.Reflection;
public static class ExtenxionMethod
{
    public static string ExtGetAttributeDescription(this Enum en)
    {
        Type type = en.GetType();
        MemberInfo[] members = type.GetMember(en.ToString());
        // 如果沒有任何attribute則報錯
        if (members == null)
            throw new ArgumentException("There is no property in this attribute");
        object[] attributes = members[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
        // 如果attribute中沒有description則報錯
        if (attributes == null)
            throw new ArgumentException("There is no attribute in this description");
        return ((DescriptionAttribute)attributes[0]).Description;
    }
}
呼叫方式
Status status = (Status)10;
Console.WriteLine(status.ExtGetAttributeDescription());
Console.ReadKey();
印出來的結果

這樣就可以列舉也可以傳回適合讓使用者觀看的資料了
歡迎您的加入,讓這個社群更加美好!