在编程中,我们经常会遇到null检查的大量出现的情况。我说的是:
if (doc != null)
{
if (doc.Element != null)
{
... and so on
}
else
throw new Exception("Element cannot be null");
} else {
throw new Exception("document cannot be null");
}基本上,整个事情变成了一个不可读的噩梦,所以我想知道:是否有更简单的方法来描述我想要做的事情呢?(除了空检查之外,我还不时得到类似于string.IsNullOrEmpty的东西。)
接受了答案:--我接受了有此链接的答案,因为所描述的方法是创新的,也正是我想要的。谢了肖恩!
发布于 2009-01-09 19:10:00
查看本文:一种流畅的C#参数验证方法
它是由一个Paint.NET开发人员编写的。他使用扩展方法来简化和清理空检查代码。
发布于 2009-01-09 18:25:17
将它们向前推到函数的开头,并将它们排除在执行工作的代码中。如下所示:
if (doc == null)
throw new ArgumentNullException("doc");
if (doc.Element == null)
throw new ArgumentException("Element cannot be null");
AndSoOn(); 发布于 2009-01-09 18:24:13
如果您只是要抛出一个异常,为什么不让语言运行时为您抛出它呢?
doc.Element.whatever("foo");您仍将得到一个NullPointerException (或C#中的任何内容),其中包含完整的跟踪信息。
https://stackoverflow.com/questions/429112
复制相似问题