【发布时间】: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
【问题讨论】:
-
可以让用户通过,判断是否为空
-
您应该使用
if(word1 == null) throw new ArgumentNullException("word1");处理Add中的这种情况。编译器如何知道一个对象在编译时是否为null?而不是Add(null, "world");,也可以是Add(maybeNullOrNot, "world");。