C#特性属性验证
记得以前的 if(model.Validate()){...}
1.abstract继承类
public abstract class ValidateAttribute:Attribute { public abstract bool Validate(object age); }
2.继承实现类(可以用来验证属性和字段的)
public static class AttributeExtends { public static bool Validate<T>(this T t) where T : class { Type type = t.GetType(); //循环属性 foreach (var prop in type.GetProperties()) { if (prop.IsDefined(typeof(ValidateAttribute), true)) { object ovalue = prop.GetValue(t); foreach (ValidateAttribute attribute in prop.GetCustomAttributes(typeof(ValidateAttribute), true)) { if (!attribute.Validate(ovalue)) { return false; } } } } //循环字段 foreach (var field in type.GetFields()) { if (field.IsDefined(typeof(ValidateAttribute), true)) { object ovalue = field.GetValue(t); foreach (ValidateAttribute attribute in field.GetCustomAttributes(typeof(ValidateAttribute), true)) { if (!attribute.Validate(ovalue)) { return false; } } } } return true; } }
3.验证类(验证值需要大于_minAge)
public class StudentAttribute: ValidateAttribute { public int _minAge; public StudentAttribute(int minAge) { _minAge = minAge; } public override bool Validate(object oValue) { return oValue != null && int.TryParse(oValue.ToString(), out int lValue) && lValue > _minAge; } }
4.类上特性的应用
public class Student { public int ID { get; set; } public string Name { get; set; } public string Sex { get; set; } [StudentAttribute(minAge:18)] public int Age { get; set; } }
5.使用
static void Main(string[] args) { try { Console.WriteLine("Start"); Student student = new Student { ID = 1, Sex ="男", Name = "dzw", Age = 12 }; Console.WriteLine(student.Validate()); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); }