C# API中模型与它们的接口设计详解

2020-01-05 09:30:12王冬梅
  • 清除错误:从对象中删除所有已触发的验证错误。

    对于这种模型,模型对象将从初始状态开始。如果它在显示给用户之前已经包含了部分值,则应该在向用户显示之前调用清除错误的方法。

    当用户修改某个字段时,只验证该字段。然后,在保存之前,可以调用验证方法强制对模型进行全面检查,包括非用户修改的属性。

    理论上的验证接口

    我认为.NET的验证接口应该看起来像这样:

    
    public interface IValidatable
    {
     /// This forces the object to be completely revalidated.
     bool Validate();
    
     /// Clears the error collections and the HasErrors property
     void ClearErrors();
    
     /// Returns True if there are any errors.
     bool HasErrors { get; }
    
     /// Returns a collection of object-level errors.
     ReadOnlyCollection<ValidationResult> GetErrors();
    
     /// Returns a collection of property-level errors.
     ReadOnlyCollection<ValidationResult> GetErrors(string propertyName);
    
     /// Returns a collection of all errors (object and property level).
     ReadOnlyCollection<ValidationResult> GetAllErrors();
    
     /// Raised when the errors collection has changed.
     event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
    }

    你可以在Tortuga Anchor库中看到这个接口的实现。

    IValidatableObject

    如果不简要讨论下IValidatableObject接口,那就是我的失职。这个接口只有一个方法IEnumerable<ValidationResult> Validate(ValidationContext validationContext)。

    我很喜欢这个方法,因为它可以触发对象的完整验证,所以它可以解决空表单问题。它返回ValidationResult对象,比原始字符串要好得多。