0

在以下场景中,我使用 IValidatableObject 来验证复杂对象。

public class Foo {
    [Required]
    public Bar Foobar { get; set; }
}

public class Bar : IValidatableObject {
    public int Id { get; set; }
    public string Name { get; set; }
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)  {
        // check if the current property instance is decorated with the Required attribute
        if(TheAboveConditionIsTrue) {
            // make sure the Name property is not null or empty
        }
    }
}

我不知道这是否是最好的方法,如果不是,我很乐意对解决验证的其他方法发表评论。

4

1 回答 1

0

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;
    }
}

现在将您的基类实现为FooRequiredor 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(...);
于 2012-08-06T21:29:41.077 回答