• 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);
            }
        }
  • 相关阅读:
    LIN总线学习-总线逻辑
    使用万用表测量CAN总线电压及实际电压与逻辑电瓶关系
    汽车网络和控制单元的安全威胁研究
    [CANopen] SDO的命令字
    新起点,新开始
    Git Commands
    Obsessive String
    The E-pang Palace
    最长递增子序列(LIS)
    Valid Sets
  • 原文地址:https://www.cnblogs.com/bjhblogs/p/12697896.html
Copyright © 2020-2023  润新知