我听说它说在编程语言中包含空引用是“十亿美元的错误”。但为什么?当然,它们会导致NullReferenceExceptions,但是那又如何呢?如果使用不当,该语言的任何元素都可能成为错误的来源。
还有什么选择?我想不是这样说:
Customer c = Customer.GetByLastName("Goodman"); // returns null if not found
if (c != null)
{
Console.WriteLine(c.FirstName + " " + c.LastName + " is awesome!");
}
else { Console.WriteLine("There was no customer named Goodman. How lame!"); }
您可以这样说:
if (Customer.ExistsWithLastName("Goodman"))
{
Customer c = Customer.GetByLastName("Goodman") // throws error if not found
Console.WriteLine(c.FirstName + " " + c.LastName + " is awesome!");
}
else { Console.WriteLine("There was no customer named Goodman. How lame!"); }
但是,如何更好呢?无论哪种方式,如果您忘记检查客户是否存在,都会遇到异常。
我想,由于更具描述性,所以与NullReferenceException相比,CustomerNotFoundException的调试要容易一些。这就是全部吗?