将 null 传递给方法时出现编译时错误

Compile time error when passing null to a method

有没有办法避免将 null 传递给方法。

类似于:

   public static string Add([not null] string word1 , string word2)
        {
            return word1 + word2;
        }
![enter image description here][1]
string sentence = Add(null, "world");
                       ^^ compile error

没有。编译器不是通灵的。在某些情况下,编译器根本无法提前推断出要传递的内容。

考虑以下内容以及编译器可能如何保护您...

var rnd = new Random();
Foo(rnd.Next(2) == 0 ? "foo" : null);

由于字符串是引用类型,无法在编译时检查它。 常见且有用的事情是检查运行时并抛出 ArgumentNullException。该方法的使用者一旦使用错误就会捕获异常。

例如:

public static string Add(string word1, string word2)
{
    if (word1 == null) throw new ArgumentNullException("word1");

    return word1 + word2;
}

如果您想使用与您的示例相似的语法,您可以使用 PostSharp 代码合同。免费版允许每个项目最多使用 10 个这样的属性 类,请查看示例 PostSharp Code contracts examples。它不会给你编译器错误,但会简化代码。