首页 > 学院 > 开发设计 > 正文

特性验证实体

2019-11-17 03:06:49
字体:
来源:转载
供稿:网友

特性验证实体

特性验证实体类using System;using System.Reflection;namespace ValidateAgeAttr{    class ValidateAgeAttribute : Attribute    {        public ValidateAgeAttribute()        {        }        public ValidateAgeAttribute(int maxAge, string validateResult)        {            MaxAge = maxAge;            ValidateResult = validateResult;        }        /// <summary>        /// 允许的最大年龄        /// </summary>        public int MaxAge { get; set; }        /// <summary>        /// 验证结果        /// </summary>        public string ValidateResult { get; set; }        public void Validate(int age)        {            if (age > MaxAge)            {                ValidateResult = string.Format("无法通过验证:age({0})>MaxAge({1})", age, MaxAge);            }            else if (age <= MaxAge)            {                ValidateResult = string.Format("验证通过:age({0})<=MaxAge({1})", age, MaxAge);            }        }    }    class Person    {        public string Name { get; set; }        //[ValidateAge(MaxAge = 40)]        [ValidateAge(50, "")]        public int Age { get; set; }    }    class PRogram    {        static void Main()        {            var person = new Person { Name = "TT", Age = 20 };            Type type = person.GetType();            PropertyInfo propertyInfo = type.GetProperty("Age");            var validateAgeAttribute = (ValidateAgeAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(ValidateAgeAttribute));            Console.WriteLine("允许的最大年龄:" + validateAgeAttribute.MaxAge);            validateAgeAttribute.Validate(person.Age);            Console.WriteLine(validateAgeAttribute.ValidateResult);            Console.ReadKey();        }    }}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表