4

谁能解释为什么会发生以下情况:

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

谢谢。

4

2 回答 2

10

它调用了不同的重载。

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 方法链接

于 2010-10-21T14:31:46.223 回答
1

因为在编译时根据参数的静态类型确定调用哪个重载函数:

String.Format(null, "foo")

使用空的 IFormatProvider 和格式化字符串“foo”进行调用String.Format(IFormatProvider, string, params Object[]),这非常好。

另一方面,

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

使用 null 作为格式化字符串调用String.Format(string, object),这会引发异常。

于 2010-10-21T14:34:31.833 回答