通過特性給一個枚舉類型每個值增加一個字符串說明,用于打印或顯示。
自定義打印特性
[AttributeUsage(AttributeTargets.Field)]public class EnumDisplayAttribute : Attribute{ public EnumDisplayAttribute(string displayStr) { Display = displayStr; } public string Display { get; private set; }}
打印特性定義很簡單,只含有一個字符串屬性。
定義一個枚舉
public enum TestEnum{ [EnumDisplay("一")] one, [EnumDisplay("二")] two, three}
枚舉類型one,two均增加了一個打印特性。
增加枚舉擴展方法取得打印特性值
public static class TestEnumExtentions{ public static string Display(this TestEnum t) { var fieldName = Enum.GetName(typeof(TestEnum), t); var attributes = typeof(TestEnum).GetField(fieldName).GetCustomAttributes(false); var enumDisplayAttribute = attributes.FirstOrDefault(p => p.GetType().Equals(typeof(EnumDisplayAttribute))) as EnumDisplayAttribute; return enumDisplayAttribute == null ? fieldName : enumDisplayAttribute.Display; }}
獲取枚舉值對應的枚舉filed字符串 var fieldName = Enum.GetName(typeof(TestEnum), t);
獲取filed對應的所有自定義特性集合 var attributes = typeof(TestEnum).GetField(fieldName).GetCustomAttributes(false);
獲取EnumDisplayAttribute特性 var enumDisplayAttribute = attributes.FirstOrDefault(p => p.GetType().Equals(typeof(EnumDisplayAttribute))) as EnumDisplayAttribute
;
如存在EnumDisplayAttribute特性返回其Display值,否則返回filed字符串 return enumDisplayAttribute == null ? fieldName : enumDisplayAttribute.Display;
使用示例
class Program{ static void Main(string[] args) { TestEnum e = TestEnum.one; Console.WriteLine(e.Display()); TestEnum e1 = TestEnum.three; Console.WriteLine(e1.Display()); Console.ReadKey(); }}
輸出:
一 three擴展說明
此方法不僅可以給枚舉類型增加說明特性,亦可給自定義類型的屬性,方法增加自定義特性。。
在使用反射使GetField(string name) GetMethod(string name) GetProperty(string name)
等均需要字符串
在獲取自定義類型屬性或方法名稱字符串時可以使用 nameof
public class T{ public void Get() { } public int Num { get; set; }}T tt = new T();Console.WriteLine(nameof(tt.Num));Console.WriteLine(nameof(tt.Get));
以上所述是小編給大家介紹的c#枚舉值增加特性說明(推薦),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VEVB武林網網站的支持!
新聞熱點
疑難解答