假设我有一些基于多个属性验证对象的函数,我想创建一个接受要运行的函数的ValidationAttribute
。 IE:
[GenericValidationAttribute(NameIsValid)]
public class Person
{
public string LastName {get;set;}
public string NonIndividualName {get;set;}
// At least one required.
public bool NameIsValid()
{
return !String.IsNullOrEmpty(this.LastName) || !String.IsNullOrEmpty(this.NonIndividualName);
}
}
GenericValidationAttribute会是什么样子?也许使NameIsValid静态并接受一个Person作为参数和类似的东西?
class GenericValidationAttribute : ValidationAttribute
{
public Func<Person, bool> Delegate {get;set;}
public GenericValidaitonAttribute (Func<Person, bool> delegate)
{
this.Delegate = delegate;
}
public override bool IsValid(object value, ValidationContext context)
{
return this.Delegate.Invoke(value);
}
}