码迷,mamicode.com
首页 > Windows程序 > 详细

C#之特性

时间:2019-01-16 22:56:02      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:反编译   识别   prope   OLE   做了   var   范围   for   get   

---恢复内容开始---

特性在我们平时编码过程中是随处可见的  向MVC中的Required非空属性验证特性  序列化和反序列化特性等等  我们在字段上标记这些特性  再引用上其中的类库  就会有相应的功能  其实在这过程中  框架为我们做了一些中间处理过程  下面我们就一起来看看究竟什么是特性   它究竟是如何工作的

1.声明特性

 public class MyAttribute : Attribute
    {
        public int Min { get; set; }
        public int Max { get; set; }
        public MyAttribute() { }
        public MyAttribute(int min, int max)
        {
            this.Min = min;
            this.Max = max;
        }
    }

特性声明一般以Attribute结尾,因为以Attribute结尾一眼就能识别出是特性类   还有必须继承特性Attribute

2.特性的本质

从上面的代码可以看出特性的本质其实就是类class

反编译结果中也可以看出

技术分享图片

3.特性的使用

public class MyAttribute : Attribute
    {
        public int Min { get; set; }
        public int Max { get; set; }
        public MyAttribute() { }
        public MyAttribute(int min, int max)
        {
            this.Min = min;
            this.Max = max;
        }
        public bool Validate(Person person)
        {
            if (person.Age >= this.Min && person.Age <= this.Max) {
                Console.WriteLine("年龄不合法");
                return true;
            }
            else
            {
                return false;
            }
        }
    }
    public class Person
    {
        //规定年龄范围  18-50
        [MyAttribute(18,50)]
        public int Age { get; set; }
        public void Print()
        {
            Console.WriteLine(this.Age.ToString());
        }
    }

    public static class Validate
    {
        public static bool ValidatePerson(this Person p)
        {
            Type type = p.GetType();
            foreach (var prop in type.GetProperties())
            {
                if (prop.IsDefined(typeof(MyAttribute)))
                {
                    MyAttribute myAttribute=(MyAttribute)prop.GetCustomAttribute(typeof(MyAttribute));
                    if (myAttribute.Validate(p))
                    {
                        Console.WriteLine("验证正确");
                    }
                    else
                    {
                        Console.WriteLine("验证错误");
                        return false;
                    }
                }
            }

            return true;
        }
        
    }
 Person person = new Person() { Age=10};
                  
                    person.ValidatePerson();

 

C#之特性

标签:反编译   识别   prope   OLE   做了   var   范围   for   get   

原文地址:https://www.cnblogs.com/hzpblogs/p/10279705.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!