这是一个关于编译器在将null字面量作为参数传递时选择特定重载的问题,以string.Format重载为例。
使用null字面量作为args参数时,string.Format会抛出ArgumentNullException
异常。
string.Format("foo {0}", null);
Format方法有一些重载。
string.Format(string, object);
string.Format(string, object[]);
string.Format(IFormatProvider, string, object[]);
浏览反编译后的代码,可以看到对于空文本参数的异常是从第二个方法抛出的。然而下面的示例调用了上述第一个方法(和预期一样),接着该方法会调用第二个方法,最终返回"foo"。
string x = null;
string.Format("foo {0}", x);
string y;
string.Format("foo {0}", y = null);
但是string.Format("foo {0}", null)
调用了上面的第二个方法,并导致了一个空异常。为什么编译器会在这种情况下决定将null字面量与第二个方法签名匹配而不是第一个方法?
String.Format("Testing {0}", String.Empty)
。祝一切顺利。 - MoonKnightstring
不是一个object[]
,因此无法使用带有object[]
参数的重载,在该情况下参数的类型为string
。 - Jan