【发布时间】:2009-10-22 17:24:30
【问题描述】:
验证原始参数和“复杂数据”
验证参数
在编写方法时,应先验证参数,然后再执行任何操作。例如,假设我们有一个代表人的类:
public class Person
{
public readonly string Name;
public readonly int Age;
public class Person(string name, int age)
{
this.Name = name;
this.Age = age;
}
}
这个 Person 类有什么问题? name 和 age 在它们的值被设置为 Person 的字段之前不会被验证。 “已验证”是什么意思?应检查这两个参数是否可以接受它们的值。例如,如果 name 的值为空字符串怎么办?或者年龄的值为-10?
当值不可接受时,通过抛出 ArgumentExceptions 或派生异常来验证参数。例如:
public class Person(string name, int age)
{
if (String.IsNullOrEmpty(name))
{
throw new ArgumentNullException
("name", "Cannot be null or empty.");
}
if (age <= 0 || age > 120)
{
throw new ArgumentOutOfRangeException
("age", "Must be greater than 0 and less than 120.");
}
this.Name = name;
this.Age = age;
}
这正确地验证了 Person 的构造函数接收的参数。
乏味和恶心
因为您已经验证参数很长时间了(对吗?),您可能已经厌倦了在所有方法中编写这些 if (....) throw Argument... 语句。
我们可以做些什么来避免在您的代码中多次写入 String.IsNullOrEmpty?
【问题讨论】:
-
您有什么理由不想使用属性(而不是公共字段)并将验证放在其中?