大学IT网 - 最懂大学生的IT学习网站! QQ资料交流群:367606806
当前位置:大学IT网 > C#技巧 > 特性验证实体类using

特性验证实体类using

关键词:特性验证实体类using  阅读(744) 赞(10)

[摘要]本文是对特性验证实体类using的讲解,对学习C#编程技术有所帮助,与大家分享。
特性验证实体类
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(); } } }


相关评论