C#之特性

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

特性在我们平时编码过程中是随处可见的  向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();

猜你喜欢

转载自www.cnblogs.com/hzpblogs/p/10279705.html