请看下面的程序:
输出结果如预期:
static class Program
{
static void Extension(this string str)
{
if(str == null)
Console.WriteLine("String is null");
else
Console.WriteLine("String is not null");
}
static void Main(string[] args)
{
default(string).Extension(); // <--- warning
Extension(default(string)); // <--- no warning
}
}
输出结果如预期:
String is null
String is null
然而,C#编译器在第一行代码上给出了CS1720警告:
警告CS1720:表达式将始终导致System.NullReferenceException,因为“string”的默认值为null
我的问题是:为什么编译器会建议会出现NullReferenceException? 第一个调用Extension()
等同于第二个调用,但第二个不会产生警告。这两个调用都应该是安全的,因为this string str
是一个参数,可以安全地为null,如第二行所示。我已经能够在3.5、4.0和4.5编译器上重现这个问题,但在Mono 3.0.7上没有。
#pragma warning disable 1720
(并加上一个描述原因的漂亮注释)。 - clcto