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 } |