c# attribute 使用例子

    void test()
        {

            People test = new People();
            test.Name = "wangchao";
            test.Description = "descptiTest";

            var t = test.GetType();

            //由于我们只在Property设置了Attibute,所以先获取Property
            var properties = t.GetProperties();
            foreach (var property in properties)
            {

                //这里只做一个stringlength的验证,这里如果要做很多验证,需要好好设计一下,千万不要用if elseif去链接
                //会非常难于维护,类似这样的开源项目很多,有兴趣可以去看源码。
                if (!property.IsDefined(typeof(StringLengthAttribute), false)) continue;

                var attributes = property.GetCustomAttributes();
                foreach (var attribute in attributes)
                {
                    //这里的MaximumLength 最好用常量去做
                    var maxinumLength = (int)attribute.GetType().
                      GetProperty("MaximumLength").
                      GetValue(attribute);

                    //获取属性的值
                    var propertyValue = property.GetValue(test) as string;
                    if (propertyValue == null)
                        throw new Exception("exception info");//这里可以自定义,也可以用具体系统异常类

                    if (propertyValue.Length > maxinumLength)
                        throw new Exception(string.Format("属性{0}的值{1}的长度超过了{2}", property.Name, propertyValue, maxinumLength));
                }
            }
        }

        [AttributeUsage(AttributeTargets.Property)]
        public class StringLengthAttribute : Attribute
        {
            private int _maximumLength;
            public StringLengthAttribute(int maximumLength)
            {
                _maximumLength = maximumLength;
            }

            public int MaximumLength
            {
                get { return _maximumLength; }
            }
        }


        public class People
        {
            [StringLength(8)]
            public string Name { get; set; }

            [StringLength(15)]
            public string Description { get; set; }
        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值