2016-05-18 22 views

Trả lời

3

DescriptionAttribute was added to CoreFX, nhưng chỉ sau RC2. Vì vậy, nó sẽ có trong phiên bản RTM, nhưng không phải trong RC2. Tùy thuộc vào những gì bạn muốn làm, việc tạo thuộc tính của riêng bạn có thể hoạt động.

5

Tôi sử dụng này để thực hiện Net Framework tôi:

public static class EnumerationExtension 
{ 
    public static string Description(this Enum value) 
    { 
     // get attributes 
     var field = value.GetType().GetField(value.ToString()); 
     var attributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false); 

     // return description 
     return attributes.Any() ? ((DescriptionAttribute)attributes.ElementAt(0)).Description : "Description Not Found"; 
    } 
} 

này không làm việc cho Netcore vì vậy tôi sửa đổi nó để làm điều này:

public static class EnumerationExtension 
{ 
    public static string Description(this Enum value) 
    { 
     // get attributes 
     var field = value.GetType().GetField(value.ToString()); 
     var attributes = field.GetCustomAttributes(false); 

     // Description is in a hidden Attribute class called DisplayAttribute 
     // Not to be confused with DisplayNameAttribute 
     dynamic displayAttribute = null; 

     if (attributes.Any()) 
     { 
      displayAttribute = attributes.ElementAt(0); 
     } 

     // return description 
     return displayAttribute?.Description ?? "Description Not Found"; 
    } 
} 

Enumeration Ví dụ:

public enum ExportTypes 
{ 
    [Display(Name = "csv", Description = "text/csv")] 
    CSV = 0 
} 

Cách sử dụng mẫu để thêm tĩnh:

var myDescription = myEnum.Description(); 
Các vấn đề liên quan