加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:06:05 所属栏目:百科 来源:网络整理
导读:通过特性给一个枚举类型每个值增加一个字符串说明,用于打印或显示。 自定义打印特性 [AttributeUsage(AttributeTargets.Field)]public class EnumDisplayAttribute : Attribute{ public EnumDisplayAttribute(string displayStr) { Display = displayStr; }

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

自定义打印特性

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读