【发布时间】:2010-10-16 21:59:09
【问题描述】:
在哪里检查传递给方法的对象是否为空?
在调用方法之前是否需要测试对象?还是在使用参数的方法中?
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 有什么缺点/优点?
[EDIT2]:我刚遇到Defensive Programming,它似乎提倡在被调用者中检查 null。我想知道这是否是一种被广泛接受的做法。
【问题讨论】:
-
您可以查看此链接以进行直接分析 [如何检查对象是否已定义?][1] [1]:stackoverflow.com/questions/2537987/…