使用反射获取枚举的自定义属性Attribute

自定义Attribue:ImgAttribute

 1 [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
 2 sealed class ImgAttribute : Attribute
 3 {
 4     readonly string imgUrl;
 5 
 6     public  ImgAttribute(string imgUrl)
 7     {
 8         this.imgUrl = imgUrl;
 9     }
10     /// <summary>
11     /// 图片地址
12     /// </summary>
13     public string ImgUrl
14     {
15         get { return imgUrl; }
16     }
17 }

使用此属性的枚举:

 1 /// <summary>
 2 /// 交通方式
 3 /// </summary>
 4 public enum TransportType
 5 {
 6     [Img("/images/Airplane.jpg")]
 7     飞机=1,
 8     [Img("/images/bus.gif")]
 9     汽车=2,
10     [Img("/images/Train.jpg")]
11     火车=3,
12     [Img("/images/Ship.jpg")]
13     轮船=4,
14     [Img("/images/Foot.jpg")]
15     步行=5,
16     [Img("/images/Bike.jpg")]
17     自行车=6
18 }

使用反射获取属性值:

 1     /// <summary>
 2     /// 获取交通方式枚举的属性值(交通方式的图片地址)
 3     /// </summary>
 4     /// <param name="ttype"></param>
 5     /// <returns></returns>
 6     public static object getAttribute(TransportType ttype)
 7     {
 8         Type t = typeof(TransportType);
 9         FieldInfo[] info = t.GetFields();
10         for (int i = 0; i < info.Length; i++)
11         {
12             if (info[i].Name == ttype.ToString())
13             {
14                 var att = info[i].GetCustomAttributes(false);
15                 foreach (Attribute a in att)
16                 {
17                     if (a is ImgAttribute)
18                     {
19                         return ((ImgAttribute)a).ImgUrl;
20                     }
21                 }
22                 break;
23             }
24         }
25         return null;
26     }


 

 

 

posted @ 2010-08-08 23:42  iQingHan  阅读(2199)  评论(0编辑  收藏  举报