Foo
その実装の抽象基本クラスを作成し、IValidatableObject
そのValidate()
メソッドを仮想化します。
public abstract class FooBase : IValidatableObject
{
public string OtherProperty { get; set; }
public Bar Foobar { get; set; }
public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
//Validate other properties here or return null
if (String.IsNullOrEmpty(OtherProperty))
results.Add(new ValidationResult("OtherProperty is required", new[] { "OtherProperty" }));
return results;
}
}
FooRequired
次に、基本クラスを次のいずれかとして実装しますFooNotRequired
。
public class FooRequired : FooBase
{
public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var result = base.Validate(validationContext).ToList();
result.AddRange(Foobar.Validate(validationContext));
return result;
}
}
public class FooNotRequired : FooBase
{
//No need to override the base validate method.
}
あなたのBar
クラスはまだ次のようになります:
public class Bar : IValidatableObject
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if (String.IsNullOrEmpty(Name))
results.Add(new ValidationResult("Name is required", new[] { "Name" }));
return results;
}
}
使用法:
FooBase foo1 = new FooRequired();
foo1.Validate(...);
FooBase foo2 = new FooNotRequired();
foo2.Validate(...);