如何检查传递给方法的对象是否为null?
在调用方法之前需要对对象进行测试吗?还是在使用参数的方法内部进行检查?
public class Program
{
public static void Main(string[] args)
{
// Check if person is null here? or within PrintAge?
PrintAge(new Person { Age = 1 });
}
private static void PrintAge(Person person)
{
// check if person is null here?
Console.WriteLine("Age = {0}", person.Age);
}
}
public class Person
{
public int Age { get; set; }
}
在两个类中都进行"null"检查似乎会有太多的冗余代码。
[编辑]: 在调用者或被调用者中检查null的优缺点是什么?
[编辑2]: 我刚刚了解到防御式编程,它似乎主张在被调用者内检查null。我想知道这是否是一种广为接受的做法。