原文鏈接:http://www.feeldesignstudio.com/2013/08/data-annotations-manual
DataAnnotations在ASP.NET MVC中非常好用,但是其他時候,比如控制台程序,我們怎麼來使用它呢,直接上代碼,一個超簡單的類:
C#publicclassCustomer { [Required] publicstringName{get;set;} [Required] publicstringPhone{get;set;} [Required] publicstringEmail{get;set;} }
下面是驗證的代碼:
C#var cust=newCustomer(); var context=newValidationContext(cust,serviceProvider:null,items:null); var results=newList<ValidationResult>(); var isValid=Validator.TryValidateObject(cust,context,results); if(!isValid) { foreach(var validationResult inresults) { Console.WriteLine(validationResult.ErrorMessage); } }
實現IValidatableObject,也可以:
C#publicclassCustomer:IValidatableObject { [Required] publicstringName{get;set;} [Required] publicstringPhone{get;set;} [Required] publicstringEmail{get;set;} publicIEnumerable<ValidationResult>Validate(ValidationContext validationContext) { ... } }