特性验证实体类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(); } }}
新闻热点
疑难解答