将函数作为参数的验证属性

时间:2015-05-22 16:57:28

标签: c# .net

假设我有一些基于多个属性验证对象的函数,我想创建一个接受要运行的函数的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);
    }
}

0 个答案:

没有答案