定一个枚举如下:
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace YX.Model.QianHai { public enum IdType { [Value("0")] 身份证 = 0, [Value("1")] 户口簿 = 1, [Value("2")] 护照 = 2, [Value("3")] 军官证 = 3, [Value("4")] 士兵证 = 4, [Value("5")] 港澳居民来往内地通行证 = 5, [Value("6")] 台湾同胞来往内地通行证 = 6, [Value("7")] 临时身份证 = 7, [Value("8")] 外国人居留证 = 8, [Value("9")] 警官证 = 9, [Value("X")] 其他证件 = 10 } public static class IdTypeExtentions { public static string GetValue(this IdType idType) { return ValueAttribute.GetCustomerValue(idType); } } }
内涵一个该枚举类型的扩展方法。
由于最有一个枚举值是 引用类型,事实 枚举的值不支持 引用类型,只能获取到 值类型,
所以才有以下 自定义属性。
定义一个自定义属性:
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace YX.Model { public class ValueAttribute : Attribute { public ValueAttribute(string value) { Value = value; } public string Value { get; private set; } public static string GetCustomerValue(object code) { var ty = code.GetType(); var name = Enum.GetName(ty, code); FieldInfo field = ty.GetField(name); ValueAttribute attr = Attribute.GetCustomAttribute(field, typeof(ValueAttribute)) as ValueAttribute; return attr.Value; } } }