C# 自定义特性

  //自定义特性类

 [System.AttributeUsage(System.AttributeTargets.Field |System.AttributeTargets.Enum)]

    publicclass PropertiesDesc : System.Attribute
    {
        public string Desc { get; set; }
        public PropertiesDesc(string desc)
        {
            Desc = desc;
        }

    }

 

  public class PropertiesUtils
    {
        private static Dictionary<Type,Dictionary<string, string>> cache = new Dictionary<Type,Dictionary<string, string>>();


        public static string GetDescByProperties(object p)
        {
            var type = p.GetType();
            if (!cache.ContainsKey(type))
            {
                Cache(type);
            }
            var fieldNameToDesc = cache[type];
            var fieldName = p.ToString();
            returnfieldNameToDesc.ContainsKey(fieldName) ? fieldNameToDesc[fieldName] :string.Format("Can not found such desc for field `{0}` in type`{1}`", fieldName, type.Name);
        }


        private static void Cache(Type type)
        {
            var dict = new Dictionary<string,string>();
            cache.Add(type, dict);
            var fields = type.GetFields();
            foreach (var field in fields)
            {
                var objs =field.GetCustomAttributes(typeof(PropertiesDesc), true);
                if (objs.Length > 0)
                {
                   dict.Add(field.Name, ((PropertiesDesc)objs[0]).Desc);
                }
            }
        }
    }

//枚举对象

 public enumWeekday
    {
        [PropertiesDesc("星期一")]
        Monday = 1,


        [PropertiesDesc("星期二")]
        Tuesday = 2,


        [PropertiesDesc("星期三")]
        Wednesday = 3,


        [PropertiesDesc("星期四")]
        Thursday = 4,


        [PropertiesDesc("星期五")]
        Friday = 5,


        [PropertiesDesc("星期六")]
        Saturday = 6,


        [PropertiesDesc("星期日")]
        Sunday = 6
    }

 

调用:

 var str =PropertiesUtils.GetDescByProperties(Weekday.Friday);

            Console.Write(str);

 

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值