我有描述一個枚舉的屬性是這樣的:
public enum MyEnum
{
Name1 = 1,
[Description("Here is another")]
HereIsAnother = 2,
[Description("Last one")]
LastOne = 3
}
我發現這段代碼的基礎上檢索說明Enum
public static string GetEnumDescription(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();
}
這讓我寫這樣的代碼:
var myEnumDescriptions = from MyEnum n in Enum.GetValues(typeof(MyEnum))
select new { ID = (int)n, Name = Enumerations.GetEnumDescription(n) };
我想要做的是,如果我知道枚舉值(例如1) - 我如何檢索描述?換句話說,我如何將一個整數轉換爲一個「枚舉值」傳遞給我的GetDescription方法?
(!屬性= NULL)永遠是真實的,否則是多餘的。描述是System.ComponentModel – Jeff 2014-07-17 23:00:46
。正是我想要的。我知道這會很簡單!現在,如果stackoverflow會讓我接受這個答案......它說我需要等待7分鐘。 – 2015-12-21 15:10:52