Java和C#下的參數驗證辦法。本站提示廣大學習愛好者:(Java和C#下的參數驗證辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是Java和C#下的參數驗證辦法正文
參數的輸出和驗證成績是開辟時常常碰到的,普通的驗證辦法以下:
public bool Register(string name, int age) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException("name should not be empty", "name"); } if (age < 10 || age > 70) { throw new ArgumentException("the age must between 10 and 70","age"); } //... }
如許做當需求更改的時刻,要修改的代碼響應的也比擬多,如許比擬費事,比來接觸到了Java和C#下2種便利的參數驗證辦法,簡略的引見下。
Java參數驗證:
采取谷歌的guava下的一個幫助類:
import com.谷歌.common.base.Preconditions;
示例代碼:
public static void checkPersonInfo(int age, String name){ Preconditions.checkNotNull(name, "name為null"); Preconditions.checkArgument(name.length() > 0, "name的長度要年夜於0"); Preconditions.checkArgument(age > 0, "age必需年夜於0"); System.out.println("a person age: " + age + ", name: " + name); } public static void getPostCode(String code){ Preconditions.checkArgument(checkPostCode(code),"郵政編碼不相符請求"); System.out.println(code); } public static void main(String[] args) { try { checkPersonInfo(10,"fdsfsd"); checkPersonInfo(10,null); checkPersonInfo(-10,"fdsfsd"); getPostCode("012234"); } catch (Exception e) { e.printStackTrace(); } }
當參數不知足請求的時刻,拋出異常信息,異常中攜帶的信息為前面自界說的字符串,如許寫就便利多了。
C#參數驗證:
采取FluentValidation這個類庫,參考地址鄙人面。
應用辦法:
一個簡略的Person類:
public class Person { public string Name { set; get; } public int Age { set; get; } public Person(string name, int age) { Name = name; Age = age; } }
Person的驗證類:
public class PersonValidator : AbstractValidator<Person> { public PersonValidator() { RuleFor(x => x.Name).NotEmpty().WithMessage("姓名不克不及為空"); RuleFor(x => x.Name).Length(1,50).WithMessage("姓名字符不克不及跨越50"); RuleFor(x => x.Age).GreaterThan(0).WithMessage("年紀必需要年夜於0"); } private bool ValidName(string name) { // custom name validating logic goes here return true; } }
應用:
class Program { static void Main(string[] args) { Person customer = new Person(null,-10); PersonValidator validator = new PersonValidator(); ValidationResult results = validator.Validate(customer); bool validationSucceeded = results.IsValid; IList<ValidationFailure> failures = results.Errors; foreach (var failure in failures) { Console.WriteLine(failure.ErrorMessage); } Console.ReadKey(); } }
FluentValidation的應用文檔:http://fluentvalidation.codeplex.com/documentation
以上就是小編為年夜家帶來的Java和C#下的參數驗證辦法的全體內容了,願望對年夜家有所贊助,多多支撐~