3.特性Attribute

通过反射可以从类型、属性、方法中获取特性实例,要求先isdefined检测,再实例化

程序运行时可以找到特性,那就可以发挥的作用=》提供额外的信息、行为

特性本身是没有用的

特性是在编译时确定,不能用变量

//设置特性使用范围
[AttributeUsage(AttributeTargets.xxx)]

  

字段验证例子:验证字段长度

LongAttribute.cs

[AttributeUsage(AttributeTargets.Property)]
    public class LongAttribute : Attribute
    {
        protected long Max { get; private set; }
        protected long Min { get; private set; }
        public LongAttribute(long max,long min)
        {
            Max = max;
            Min = min;
        }

        public bool Validate(object oValue)
        {
            if (oValue != null && long.TryParse(oValue.ToString(), out long longValue) && longValue > Min && longValue < Max)
                return true;
            return false;
        }
    }

AttrbuteExtend.cs

public static class AttrbuteExtend
    {
        public static bool ValidateExtend<T>(T t)
        {
            Type type = t.GetType();
            foreach(var property in type.GetProperties())
            {
                var value = property.GetValue(t);
                if (property.IsDefined(typeof(LongAttribute), true))
                {
                    LongAttribute longAttribute = (LongAttribute)property.GetCustomAttribute(typeof(LongAttribute), true);
                    return longAttribute.Validate(value);
                }
            }
            return true;
        }
    }

Student.cs

public class Student
    {
        [Long(3,6)]
        public long QQ { get; set; }
    }

Programe.cs

class Program
    {
        static void Main(string[] args)
        {
            var student = new Student()
            {
                QQ = 111111111111
            };

            AttrbuteExtend.ValidateExtend(student);
        }
    }
原文地址:https://www.cnblogs.com/bjhblogs/p/12697896.html