使用反射获取枚举的自定义属性Attribute及其他使用方式
2012-02-07 13:02 ※森林小居※ 阅读(2344) 评论(2) 编辑 收藏 举报自定义Attribue:ImgAttribute
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] sealed class ImgAttribute : Attribute { readonly string imgUrl; public ImgAttribute(string imgUrl) { this.imgUrl = imgUrl; } /// <summary> /// 图片地址 /// </summary> public string ImgUrl { get { return imgUrl; } } }
使用此属性的枚举:
/// <summary> /// 交通方式 /// </summary> public enum TransportType { [Img("/images/Airplane.jpg")] 飞机=1, [Img("/images/bus.gif")] 汽车=2, [Img("/images/Train.jpg")] 火车=3, [Img("/images/Ship.jpg")] 轮船=4, [Img("/images/Foot.jpg")] 步行=5, [Img("/images/Bike.jpg")] 自行车=6 }
使用反射获取属性值:
/// <summary> /// 获取交通方式枚举的属性值(交通方式的图片地址) /// </summary> /// <param name="ttype"></param> /// <returns></returns> public static object getAttribute(TransportType ttype) { Type t = typeof(TransportType); FieldInfo[] info = t.GetFields(); for (int i = 0; i < info.Length; i++) { if (info[i].Name == ttype.ToString()) { var att = info[i].GetCustomAttributes(false); foreach (Attribute a in att) { if (a is ImgAttribute) { return ((ImgAttribute)a).ImgUrl; } } break; } } return null; }
将指定的枚举类型转换成List方式代码如下:
/// <summary> /// 将指定枚举类型转换成List,用来绑定ListControl /// </summary> /// <param name="EnumType">枚举类型</param> /// <param name="SelectFirst">是否需要第一项选择</param> /// <param name="FirstItem">第一项选择的内容,0设置为Text,1设置为Value,多余的不设。可以为空或不传</param> /// <returns></returns> public static List<ListItem> ConvertEnumToListItems(Type EnumType, bool SelectFirst, params string[] FirstItem) { if (EnumType.IsEnum == false) { return null; } List<ListItem> ListResult = new List<ListItem>(); Type TypeDescription = typeof(DescriptionAttribute); FieldInfo[] Fields = EnumType.GetFields(); string StrText = string.Empty; string StrValue = string.Empty; foreach (FieldInfo Field in Fields) { if (Field.IsSpecialName) continue; StrValue = Field.GetRawConstantValue().ToString(); object[] arr = Field.GetCustomAttributes(TypeDescription, true); if (arr.Length > 0) { StrText = (arr[0] as DescriptionAttribute).Description; } else { StrText = Field.Name; } ListResult.Add(new ListItem(StrText,StrValue)); } if (SelectFirst) { if (FirstItem != null && FirstItem.Length > 1) { ListResult.Insert(0, new ListItem(FirstItem[0], FirstItem[1])); } else if (FirstItem != null && FirstItem.Length == 1) { ListResult.Insert(0, new ListItem(FirstItem[0], "0")); } else { ListResult.Insert(0, new ListItem("请选择", "0")); } } return ListResult; }
public class ListItem { public ListItem() { } public ListItem(string EnumName, string EnumValue) { this.EnumName = EnumName; this.EnumValue = EnumValue; } public string EnumName { get; set; } public string EnumValue { get; set; } }