【问题标题】:Compile time error when passing null to a method将 null 传递给方法时出现编译时错误
【发布时间】:2015-03-27 10:12:42
【问题描述】:

有没有办法避免将 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

【问题讨论】:

标签: c# methods


【解决方案1】:

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

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

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

【讨论】:

  • @TimSchmelter:已更正! :)
  • 在带有 Roslyn 的 Visual Studio 2015 上使用自定义 Code Fix 怎么样?它不应该在编译时,但我认为可以在此之前检测到。
  • @HuorSwords:运行时检查与简单地使用if(word1 == null) throw new ArgumentNullException("word1"); 自己检查相比有什么好处?该代码是自记录的,应该是方法中的第一个。
  • @YagneshCangi:我不明白你为什么不理解这个答案中的Random 示例,不是很清楚吗?编译器在任何情况下都无法知道参数是否为空。当然通过null 显然是null。但参数通常在运行时得到它的值。
  • 在这种情况下,它是 Foo("foo") 或 Foo(null),编译器可以轻松检测这两种情况。
【解决方案2】:

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

例如:

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

    return word1 + word2;
}

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2018-02-12
      • 1970-01-01
      • 2013-01-05
      • 1970-01-01
      • 1970-01-01
      • 2017-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多