我是靠谱客的博主 含糊蜡烛,这篇文章主要介绍c#枚举值增加特性说明(推荐),现在分享给大家,希望可以做个参考。

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

自定义打印特性

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
[AttributeUsage(AttributeTargets.Field)] public class EnumDisplayAttribute : Attribute { public EnumDisplayAttribute(string displayStr) { Display = displayStr; } public string Display { get; private set; } }

打印特性定义很简单,只含有一个字符串属性。

定义一个枚举

复制代码
1
2
3
4
5
6
7
8
public enum TestEnum { [EnumDisplay("一")] one, [EnumDisplay("二")] two, three }

枚举类型one,two均增加了一个打印特性。

增加枚举扩展方法取得打印特性值

复制代码
1
2
3
4
5
6
7
8
9
10
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;

使用示例

复制代码
1
2
3
4
5
6
7
8
9
10
11
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(); } }

输出:

复制代码
1
2
3
一 three 扩展说明

此方法不仅可以给枚举类型增加说明特性,亦可给自定义类型的属性,方法增加自定义特性。。

在使用反射使GetField(string name) GetMethod(string name) GetProperty(string name)等均需要字符串

在获取自定义类型属性或方法名称字符串时可以使用 nameof

复制代码
1
2
3
4
5
6
7
8
9
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#枚举值增加特性说明(推荐),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对靠谱客网站的支持!

最后

以上就是含糊蜡烛最近收集整理的关于c#枚举值增加特性说明(推荐)的全部内容,更多相关c#枚举值增加特性说明(推荐)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(114)

评论列表共有 0 条评论

立即
投稿
返回
顶部