Rob*_*vey 9 c# validation .net-3.5 data-annotations
.NET Framework中是否有一种方法可以将某些方法或验证器用于使用Data Annotations修饰其类,并接收错误集合?
我看到有一种方法可以在.NET 4.x中执行此操作.但.NET 3.5中是否有类似的机制?
Pat*_*gee 12
通过一些反思,您可以构建自己的验证器,扫描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<string> 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之间!
小智 7
Linq版本
public static class Validator
{
    public static IEnumerable<string> Validate(object o)
        {
            return TypeDescriptor
                .GetProperties(o.GetType())
                .Cast<PropertyDescriptor>()
                .SelectMany(pd => pd.Attributes.OfType<ValidationAttribute>()
                                    .Where(va => !va.IsValid(pd.GetValue(o))))
                                    .Select(xx => xx.ErrorMessage);
        }
    }