相关疑难解决方法(0)

在哪里检查对象是否为空?

在哪里检查传递给方法的对象是否为空?

在调用方法之前是否需要测试对象?或者在使用参数的方法中?

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; }
}
Run Code Online (Sandbox Code Playgroud)

在两个类中进行"空"检查似乎是太多的冗余代码.

[编辑]:在调用者或被调用者中检查空值会有什么好处?

[编辑方面2]:我刚刚遇到防御性编程,似乎它主张在被调用者中检查null.我想知道这是否是一种被广泛接受的做法.

.net null

18
推荐指数
3
解决办法
6010
查看次数

标签 统计

.net ×1

null ×1