参数验证方式
1. 一般方法
1.1 手动验证
最为普遍常见,略。
1.2 使用扩展方法验证
在C#3.0 中,引入了扩展方法,可以以一种更优雅的方式来进行参数验证,如:
1 //参数辅助类 2 public static class ArgumentHelper 3 { 4 public static void RequireRange(this int value, int minValue, int maxValue, string argumentName) 5 { 6 if (value > maxValue || value < minValue) 7 { 8 throw new ArgumentException(string.Format("The value must be between {0} and {1}", minValue, maxValue), argumentName); 9 } 10 } 11 12 public static void RequireNotNullOrEmpty(this string value, string argumentName) 13 { 14 if (string.IsNullOrEmpty(value)) 15 { 16 throw new ArgumentException("The value can't be null or empty", argumentName); 17 } 18 } 19 } 20 21 //用户注册 22 public bool Register(string name, int age) 23 { 24 name.RequireNotNullOrEmpty("name"); 25 age.RequireRange(10,70,"age"); 26 //insert into db 27 }