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);
            }
        }
  • 相关阅读:
    PHPMyAdmin Docker
    Appium环境搭建-Mac版本
    上传项目到GitHub遇到的错误
    上传项目到GitHub(总结)
    C++ 简单代码,语法参照
    vs2010学习
    线性拟合-实验报告
    我的图形学程序
    网页版 连连看 html5实现
    带无线功能的笔记本 配置无线局域网 共享上网
  • 原文地址:https://www.cnblogs.com/bjhblogs/p/12697896.html
Copyright © 2011-2022 走看看