• c# 使用特性封装提供额外行为Validate验证


    namespace AttributeTest
    {
        //使用特性封装提供额外行为Validate验证
        class Program
        {
            static void Main(string[] args)
            {
                Student student = new Student()
                {
                    Name = "123",
                    QQ = 20000
                };
                Console.WriteLine(student.Validate());
                Console.ReadLine();
            }
        }
    }
    namespace AttributeTest
    {
        //学生实体类 
        public class Student
        {
            [Required]
            public string Name { get; set; }
            [Validate(10000,99999)]
            public long QQ { get; set; }
        }
    }
    namespace AttributeTest
    {
        //特性attribute;就是一个类,直接继承/间接继承自Attribute父类
        //约定俗成用Attribute结尾,标记时就可以省略掉
        public abstract class AbstractValidateAttribute : Attribute
        {
            public abstract bool Validate(object value);
        }
    }
        //验证不可为null或者空
        public class RequiredAttribute : AbstractValidateAttribute
        {
    
            public override bool Validate(object value)
            {
                return value != null && value.ToString() != "";
            }
        }
        //验证是否在范围内
        [AttributeUsage(AttributeTargets.Property)]
        public class ValidateAttribute : AbstractValidateAttribute
        {
            private long _Min;
            private long _Max;
            public ValidateAttribute(long min, long max)
            {
                _Max = max;
                _Min = min;
            }
            public override bool Validate(object value)
            {
                return value != null && long.TryParse(value.ToString(), out long Lvalue) && Lvalue > _Min && Lvalue < _Max;
            }
        }
        public static class AttributeExtend
        {
            //从类型  属性  方法 都可以获取特性实例,要求先IsDefined检测  再获取(实例化)
            public static bool Validate<T>(this T t)
            {
                Type type = t.GetType();
                foreach (PropertyInfo item in type.GetProperties())
                {
                    if (item.IsDefined(typeof(AbstractValidateAttribute), true))
                    {
                        object ovalue = item.GetValue(t);
    
                        AbstractValidateAttribute attribute = (AbstractValidateAttribute)item.GetCustomAttribute(typeof(AbstractValidateAttribute), true);
    
                        if (!attribute.Validate(ovalue))
                            return false;
                    }
                }
                return true;
    
            }
        }
  • 相关阅读:
    扫描线算法
    [Baltic 2001]Mars Maps
    Lost Cow
    李超线段树
    多种方法求解Pku3468 A Simple Problem with Integers
    陈老师的福利
    leetcode 673. 最长递增子序列的个数
    #10043.「一本通 2.2 例 1」剪花布条
    PTA7-1
    6-1 实验三哈夫曼树 (15分)
  • 原文地址:https://www.cnblogs.com/wangdash/p/11967399.html
Copyright © 2020-2023  润新知