thể trùng lặp:
Getting attributes of Enum’s valueLàm thế nào để có được mô tả C# Enum từ giá trị?
Tôi có một enum với Mô tả các thuộc tính như thế này:
public enum MyEnum
{
Name1 = 1,
[Description("Here is another")]
HereIsAnother = 2,
[Description("Last one")]
LastOne = 3
}
tôi thấy chút mã này để lấy mô tả dựa trên một 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();
}
này cho phép tôi để viết mã như:
var myEnumDescriptions = from MyEnum n in Enum.GetValues(typeof(MyEnum))
select new { ID = (int)n, Name = Enumerations.GetEnumDescription(n) };
Những gì tôi muốn làm là nếu tôi biết giá trị enum (ví dụ 1) - làm cách nào tôi có thể truy xuất mô tả? Nói cách khác, làm cách nào tôi có thể chuyển đổi một số nguyên thành "Giá trị enum" để chuyển sang phương thức GetDescription của tôi?
(! Thuộc tính = null) sẽ luôn luôn được đúng và khác là thừa. – Jeff
không gian tên cần thiết cho Mô tả là System.ComponentModel –