如何使用.NET Framework 3.5中的数据注释对C#类进行属性validation?

.NET Framework中是否有一种方法可以将一些对象实例与一个对象实例交给一个方法或validation器,该对象实例的类用Data Annotations修饰,并接收一组错误?

我看到有一种方法可以在.NET 4.x中执行此操作 。 但.NET 3.5中是否有类似的机制?

通过一些reflection,您可以构建自己的validation器,该ValidationAttributes器扫描您拥有的属性上的ValidationAttributes 。 它可能不是一个完美的解决方案,但如果你只限于使用.NET 3.5,这似乎是一个轻量级的解决方案,希望你能得到它。

 static void Main(string[] args) { Person p = new Person(); p.Age = 4; var results = Validator.Validate(p); results.ToList().ForEach(error => Console.WriteLine(error)); Console.Read(); } // Simple Validator class public static class Validator { // This could return a ValidationResult object etc public static IEnumerable Validate(object o) { Type type = o.GetType(); PropertyInfo[] properties = type.GetProperties(); Type attrType = typeof (ValidationAttribute); foreach (var propertyInfo in properties) { object[] customAttributes = propertyInfo.GetCustomAttributes(attrType, inherit: true); foreach (var customAttribute in customAttributes) { var validationAttribute = (ValidationAttribute)customAttribute; bool isValid = validationAttribute.IsValid(propertyInfo.GetValue(o, BindingFlags.GetProperty, null, null, null)); if (!isValid) { yield return validationAttribute.ErrorMessage; } } } } } public class Person { [Required(ErrorMessage = "Name is required!")] public string Name { get; set; } [Range(5, 20, ErrorMessage = "Must be between 5 and 20!")] public int Age { get; set; } } 

这会将以下内容打印到控制台:

名字是必需的!
必须在5到20之间!

Linq版本

 public static class Validator { public static IEnumerable Validate(object o) { return TypeDescriptor .GetProperties(o.GetType()) .Cast() .SelectMany(pd => pd.Attributes.OfType() .Where(va => !va.IsValid(pd.GetValue(o)))) .Select(xx => xx.ErrorMessage); } } 

那些数据注释东西主要在另一个框架的上下文中工作,例如。 MVC w / Razor,Fluent等没有其他框架,注释就是这样,它们是标记代码,并且需要框架/额外代码来进行解释。

注释本身并不是真正的AOP / Intercept,因此注释不会做任何事情,直到用注释修饰的对象被提交到知道如何解释/解析标记代码的中间框架(通常通过.reflection)。

对于可以使注释本质上工作的真正AoP,您将需要类似PostSharp / Unity等的东西。这些框架在运行/编译时修改IL并重新路由原始代码。