一个扩展方法
public static class AttachDataExtensions
{
public static object GetAttachedData(this ICustomAttributeProvider provider, object key)
{
var attributes = (AttachDataAttribute[])provider.GetCustomAttributes(
typeof(AttachDataAttribute), false);
return attributes.First(a => a.Key.Equals(key)).Value;
}
public static T GetAttachedData<T>(
this ICustomAttributeProvider provider, object key)
{
return (T)provider.GetAttachedData(key);
}
public static object GetAttachedData(this Enum value, object key)
{
return value.GetType().GetField(value.ToString()).GetAttachedData(key);
}
public static T GetAttachedData<T>(this Enum value, object key)
{
return (T)value.GetAttachedData(key);
}
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
public class AttachDataAttribute : Attribute
{
public AttachDataAttribute(object key, object value)
{
this.Key = key;
this.Value = value;
}
public object Key { get; private set; }
public object Value { get; private set; }
}
public enum AgeRange
{
[AttachData(AgeRangeAttachData.Text, "18岁及以下")]
LessThan18,
[AttachData(AgeRangeAttachData.Text, "19至29岁")]
From19To29,
[AttachData(AgeRangeAttachData.Text, "30岁及以上")]
Above29
}
public enum AgeRangeAttachData
{
Text
}
浙公网安备 33010602011771号