防止空参数导致 'NullReferenceException'

Preventing a null argument from causing a 'NullReferenceException'

在我的库中,我经常公开将字符串作为参数的方法。我是否应该始终检查字符串参数是否等于 null?或者可以忽略 null 值导致 NullreferenceException 的可能性吗?

示例:

public static void Parse(string line)
{
     string[] splits = line.Split(' ');
}

在此方法中,line 可以是 null,这会导致 Parse 抛出 NullreferenceException。 (具体来说,因为试图在 null 值上调用 Split。)我是否应该检查 line 是否为 null 以防止抛出异常?

你绝对应该防止它被抛出。

您正在设计一个库并公开一个库方法,因此您的消费者不必深入研究您的源代码来了解为什么抛出完全可以预防的 NullReferenceException

根据该语句后面的代码的作用,您要么提供默认值,要么抛出 ArgumentNullException:

line = line ?? "";

或者:

if (line == null)
{
    throw new ArgumentNullException("line");
}

您的问题涉及是否建议在尝试在方法中取消引用之前检查传递给方法的引用类型参数是否 null

Microsoft 建议您应该进行此项检查。具体来说,如果您使用 Code Analysis tool in Visual Studio, it will issue warning CA1062: Validate arguments of public methods 检查 Parse 方法。这是本文的介绍性文字:

Cause

An externally visible method dereferences one of its reference arguments without verifying whether that argument is null (Nothing in Visual Basic).

Rule Description

All reference arguments that are passed to externally visible methods should be checked against null. If appropriate, throw a ArgumentNullException when the argument is null.

If a method can be called from an unknown assembly because it is declared public or protected, you should validate all parameters of the method. If the method is designed to be called only by known assemblies, you should make the method internal and apply the InternalsVisibleToAttribute attribute to the assembly that contains the method.

How to Fix Violations

To fix a violation of this rule, validate each reference argument against null.

When to Suppress Warnings

You can suppress a warning from this rule if you are sure that the dereferenced parameter has been validated by another method call in the function.

请参阅 CA1062 文章中的第二个代码示例,了解使用私有方法验证参数有帮助(甚至可能必不可少)的场景。