如何管理无效检查的冲击?

Dmi*_*ruk 22 .net c#

通常,在编程中我们会遇到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");
}
Run Code Online (Sandbox Code Playgroud)

基本上,整个事情变成了一个难以理解的噩梦,所以我想知道:有没有更简单的方法来描述我上面要做的事情?(除了空检查,我string.IsNullOrEmpty不时会得到类似的东西.)

接受的答案:我接受了具有此链接的答案,因为所描述的方法具有创新性,正是我想要的.谢谢肖恩!

Sha*_*awn 25

看看这篇文章:一种流畅的C#参数验证方法

它由一个Paint.NET开发人员编写.他使用扩展方法来简化和清理空检查代码.


Dan*_*ego 17

将它们向前推到函数的开头,并将它们从执行工作的代码部分中取出.像这样:

if (doc == null)
    throw new ArgumentNullException("doc");
if (doc.Element == null)
    throw new ArgumentException("Element cannot be null");
AndSoOn(); 
Run Code Online (Sandbox Code Playgroud)


Gre*_*ill 13

如果你只是想抛出异常,为什么不让语言运行时为你抛出它?

doc.Element.whatever("foo");
Run Code Online (Sandbox Code Playgroud)

您仍将获得具有完整回溯信息的NullPointerException(或C#中的任何内容).


Cra*_*raz 8

您可能对Spec#感兴趣:

Spec#是API契约的形式语言,它使用非空类型,前置条件,后置条件,对象不变量和模型程序(将整个运行历史考虑在内的行为契约)构造扩展C# .

你可以让调用者负责确保参数不为null.Spec#使用感叹号表示:

public static void Clear(int[]! xs) // xs is now a non-null type
{
    for (int i = 0; i < xs.Length; i++)
    {
        xs[i] = 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在是Spec#编译器,它将检测可能的空引用:

int[] xs = null;
Clear(xs);   // Error: null is not a valid argument
Run Code Online (Sandbox Code Playgroud)

作为旁注,您可能还想确保您没有违反得墨忒耳法则.


归档时间:

查看次数:

2408 次

最近记录:

11 年,9 月 前