在使用Enum時,有時候需要定義說明文字以利在UI上呈現,所以可以加入屬性Description,於是在網路上找了一下,結果只有找到取得名稱的方式,如下所示
using System;
public class GetNameTest {
enum Colors { Red, Green, Blue, Yellow };
enum Styles { Plaid, Striped, Tartan, Corduroy };
public static void Main() {
Console.WriteLine("The 4th value of the Colors Enum is {0}", Enum.GetName(typeof(Colors), 3));
Console.WriteLine("The 4th value of the Styles Enum is {0}", Enum.GetName(typeof(Styles), 3));
}
}
來源:https://msdn.microsoft.com/zh-tw/library/system.enum.getname(v=vs.110).aspx
所以只好自已寫擴充方法來新增
public static class HelpExtensions
{
public static string GetEnumDescription(this Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
//若取不到屬性,則取名稱
if ((attributes != null) && (attributes.Length > 0))
return attributes[0].Description;
else
return value.ToString();
}
}
public enum MessageType
{
[Description("Create")]
Creation = 1,
[Description("Update")]
Updating = 2,
[Description("Del")]
Deletion = 3,
[Description("Select")]
Selection = 4
}
//使用方式
var messageType = MessageType.Deletion.GetEnumDescription();
Console.WriteLine("Ouput:" + messageType);
//顯示結果
//Output:Del
Read more...