定义自定义属性AttachDataAttribute

代码
/// <summary>
/// 附加数据属性
/// </summary>
[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 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);
    }
    /// <summary>
    /// 获得枚举类型的注释
    /// </summary>
    /// <param name="enumObject"></param>
    /// <returns></returns>
    public static string GetText(this Enum enumObject)
    {
        return enumObject.GetAttachedData<string>(AttachData.Text);
    }
}

定义一个Enum(AttachData)来表示定义属性的类型

代码
public enum AttachData
{
    Text
}

为枚举项加上自定义属性

代码
public enum ProposalState
{
    /// <summary>
    /// 未提交
    /// </summary>
    [AttachData(AttachData.Text, "未提交")]
    WeiTiJiao = 1,

    /// <summary>
    /// 待审查
    /// </summary>
    [AttachData(AttachData.Text, "待审查")]
    DaiShenCha = 2,

    /// <summary>
    /// 待交办
    /// </summary>
    [AttachData(AttachData.Text, "待交办")]
    DaiJiaoBan = 3,

    /// <summary>
    /// 待承办
    /// </summary>
    [AttachData(AttachData.Text, "待承办")]
    DaiChengBan = 4,

    /// <summary>
    /// 已办结
    /// </summary>
    [AttachData(AttachData.Text, "已办结")]
    YiBanJie = 5
}

得到枚举项的自定义属性

代码
ProposalState.DaiChengBan.GetText();
posted on 2010-04-07 20:10  znyin  阅读(439)  评论(0编辑  收藏  举报