C#自定义Attribute值的获取与优化

发表于:2015-11-11 10:56

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:junjieok    来源:51Testing软件测试网采编

  C#自定义Attribute值的获取是开发中会经常用到的,一般我们的做法也就是用反射进行获取的,代码也不是很复杂。
  1、首先有如下自定义的Attribute
1     [AttributeUsage(AttributeTargets.All)]
2     public sealed class NameAttribute : Attribute
3     {
4         private readonly string _name;
5
6         public string Name
7         {
8             get { return _name; }
9         }
10
11         public NameAttribute(string name)
12         {
13             _name = name;
14         }
15     }
  2、定义一个使用NameAttribute的类
  1     [Name("dept")]
  2     public class CustomAttributes
  3     {
  4         [Name("Deptment Name")]
  5         public string Name { get; set; }
  6
  7         [Name("Deptment Address")]
  8         public string Address;
  9     }
  3、获取CustomAttributes类上的"dept"也就很简单了
  1         private static string GetName()
  2         {
  3             var type = typeof(CustomAttributes);
  4
  5             var attribute = type.GetCustomAttributes(typeof(NameAttribute), false).FirstOrDefault();
  6
  7             if (attribute == null)
  8             {
  9                 return null;
  10             }
  11
  12             return ((NameAttribute)attribute).Name;
  13         }
  以上代码就可以简单的获取,类上的Attribute的值了,但是需求往往不是这么简单的,不仅要获取类头部Attribute上的值,还要获取字段Address头部Attribute上的值。有的同学可能就觉得这还不简单呀,直接上代码
1         private static string GetAddress()
2         {
3             var type = typeof (CustomAttributes);
4
5             var fieldInfo = type.GetField("Address");
6             if (fieldInfo == null)
7             {
8                 return null;
9             }
10
11             var attribute = fieldInfo.GetCustomAttributes(typeof(NameAttribute), false).FirstOrDefault();
12
13             if (attribute == null)
14             {
15                 return null;
16             }
17
18             return ((NameAttribute) attribute).Name;
19         }
21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号