zoukankan      html  css  js  c++  java
  • 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);
            }
        }
  • 相关阅读:
    第10组 Beta冲刺(2/5)
    第10组 Beta冲刺(1/5)
    第10组 Alpha事后诸葛亮
    3月7-第十次机试课记录
    3月5-第九次机试课记录
    3月2-第八次机试课记录
    3月1-第六次机试课记录
    2月28-第五次机试课记录
    STL
    2月27-第四次机试课记录
  • 原文地址:https://www.cnblogs.com/bjhblogs/p/12697896.html
Copyright © 2011-2022 走看看