具有 null 格式的 String.Format

发布于 2024-09-28 15:04:33 字数 296 浏览 1 评论 0原文

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

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

谢谢。

Can anyone explain why the following occurs:

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

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

那请放手 2024-10-05 15:04:33

它调用不同的重载。

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 方法链接 如上所述。

Its calling a different overload.

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

MSDN Method Link describing above.

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

MSDN Method Link describing above.

童话 2024-10-05 15:04:33

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

String.Format(null, "foo")

调用 String.Format(IFormatProvider, string, params Object[]) 带有一个空的 IFormatProvider 和一个格式化字符串“foo”,这完全没问题。

另一方面,

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

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

Because which overloaded function is called gets determined at compile time based on the static type of the parameter:

String.Format(null, "foo")

calls String.Format(IFormatProvider, string, params Object[]) with an empty IFormatProvider and a formatting string of "foo", which is perfectly fine.

On the other hand,

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

calls String.Format(string, object) with null as a formatting string, which throws an exception.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文