任何人都可以解释为什么会发生以下情况:

String.Format(null, "foo") // Returns foo
String.Format((string)null, "foo") // Throws ArgumentNullException:
                                   // Value cannot be null. 
                                   // Parameter name: format

谢谢。

有帮助吗?

解决方案

它调用不同的超载。

string.Format(null, "");  
//calls 
public static string Format(IFormatProvider provider, string format, params object[] args);

MSDN方法链接 上面描述。

string.Format((string)null, "");
//Calls (and this one throws ArgumentException)
public static string Format(string format, object arg0);

MSDN方法链接 上面描述。

其他提示

因为将其重载的函数称为“在编译时间”根据参数的静态类型确定:

String.Format(null, "foo")

呼叫 String.Format(IFormatProvider, string, params Object[]) 带有一个空的iFormatProvider和“ foo”格式字符串,这很好。

另一方面,

String.Format((string)null, "foo")

呼叫 String.Format(string, object) 将null作为格式字符串,引发异常。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top