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(); } } }