我喜欢企业库中的验证应用程序块 :-)
现在我想在 Winforms 中使用 DataAnnotations,因为我们也使用 asp.net 动态数据。这样我们就有了全公司通用的技术。
而且数据注释应该更容易使用。
我怎样才能在 Winforms 中做类似于Stephen Walter 在 asp.net MVC中所做的事情?
我喜欢企业库中的验证应用程序块 :-)
现在我想在 Winforms 中使用 DataAnnotations,因为我们也使用 asp.net 动态数据。这样我们就有了全公司通用的技术。
而且数据注释应该更容易使用。
我怎样才能在 Winforms 中做类似于Stephen Walter 在 asp.net MVC中所做的事情?
我改编了在http://blog.codeville.net/category/validation/page/2/找到的解决方案
public class DataValidator
{
public class ErrorInfo
{
public ErrorInfo(string property, string message)
{
this.Property = property;
this.Message = message;
}
public string Message;
public string Property;
}
public static IEnumerable<ErrorInfo> Validate(object instance)
{
return from prop in instance.GetType().GetProperties()
from attribute in prop.GetCustomAttributes(typeof(ValidationAttribute), true).OfType<ValidationAttribute>()
where !attribute.IsValid(prop.GetValue(instance, null))
select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty));
}
}
这将允许您使用以下代码使用以下语法验证任何对象:
var errors = DataValidator.Validate(obj);
if (errors.Any()) throw new ValidationException();