首页 > 编程技术 > csharp

c#枚举值增加特性说明(推荐)

发布时间:2020-6-25 11:19

通过特性给一个枚举类型每个值增加一个字符串说明,用于打印或显示。

自定义打印特性

[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#枚举值增加特性说明(推荐),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对猪先飞网站的支持!

标签:[!--infotagslink--]

您可能感兴趣的文章: