手动执行验证属性

大多数情况下,验证属性都在框架内部使用(例如 ASP.NET)。这些框架负责执行验证属性。但是,如果要手动执行验证属性,该怎么办?只需使用 Validator 类(不需要反射)。

验证上下文

任何验证都需要一个上下文来提供有关正在验证的内容的一些信息。这可以包括各种信息,例如要验证的对象,一些属性,错误消息中显示的名称等。

ValidationContext vc = new ValidationContext(objectToValidate); // The simplest form of validation context. It contains only a reference to the object being validated.

创建上下文后,有多种方法可以进行验证。

验证对象及其所有属性

ICollection<ValidationResult> results = new List<ValidationResult>(); // Will contain the results of the validation
bool isValid = Validator.TryValidateObject(objectToValidate, vc, results, true); // Validates the object and its properties using the previously created context.
// The variable isValid will be true if everything is valid
// The results variable contains the results of the validation

验证对象的属性

ICollection<ValidationResult> results = new List<ValidationResult>(); // Will contain the results of the validation
bool isValid = Validator.TryValidatePropery(objectToValidate.PropertyToValidate, vc, results, true); // Validates the property using the previously created context.
// The variable isValid will be true if everything is valid
// The results variable contains the results of the validation

和更多

要了解有关手动验证的更多信息,请