參數(shù)的輸入和驗(yàn)證問題是開發(fā)時(shí)經(jīng)常遇到的,一般的驗(yàn)證方法如下:
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"); } //...}這樣做當(dāng)需求變動(dòng)的時(shí)候,要改動(dòng)的代碼相應(yīng)的也比較多,這樣比較麻煩,最近接觸到了Java和C#下2種方便的參數(shù)驗(yàn)證方法,簡(jiǎn)單的介紹下。
Java參數(shù)驗(yàn)證:
采用google的guava下的一個(gè)輔助類:
import com.google.common.base.Preconditions;
示例代碼:
public static void checkPersonInfo(int age, String name){  Preconditions.checkNotNull(name, "name為null");  Preconditions.checkArgument(name.length() > 0, "name的長(zhǎng)度要大于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();  } }當(dāng)參數(shù)不滿足要求的時(shí)候,拋出異常信息,異常中攜帶的信息為后面自定義的字符串,這樣寫就方便多了。
C#參數(shù)驗(yàn)證:
采用FluentValidation這個(gè)類庫(kù),參考地址在下面。
使用方法:
一個(gè)簡(jiǎn)單的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的驗(yàn)證類:
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
以上就是小編為大家?guī)淼腏ava和C#下的參數(shù)驗(yàn)證方法的全部?jī)?nèi)容了,希望對(duì)大家有所幫助,多多支持武林網(wǎng)~
新聞熱點(diǎn)
疑難解答
圖片精選