空字符串上的ToString

为什么第二个产生exception而第一个产生exception呢?

string s = null; MessageBox.Show(s); MessageBox.Show(s.ToString()); 

更新 – 我能理解的例外,令人费解的一点(对我而言)是第一部分没有显示exception的原因。 这与Messagebox没有任何关系,如下图所示。

例如:

 string s = null, msg; msg = "Message is " + s; //no error msg = "Message is " + s.ToString(); //error 

第一部分似乎是隐式地将null转换为空字符串。

因为你无法在null引用上调用实例方法ToString()

MessageBox.Show()可能实现为忽略null并打印出空消息框。

这是因为MessageBox.Show()是用pinvoke实现的,它调用本机的Windows MessageBox()函数。 哪个不介意为lpText参数获取NULL。 对于纯.NET实例方法(如ToString),C#语言有更严格的规则,它总是发出代码来validation对象不是null。 在这篇博客文章中有一些背景信息。

在你的后续问题/更新例如,在幕后调用concat

 string snull = null; string msg = "hello" + snull; // is equivalent to the line below and concat handles the null string for you. string msg = String.Concat("hello", snull); // second example fails because of the toString on the null object string msg = String.Concat("hello", snull.ToString()); //String.Format, String.Convert, String.Concat all handle null objects nicely. 

由于这个问题在Google上搜索“c#toString null”的排名很高,我想补充一点, Convert.ToString(null)方法会返回一个空字符串。

但是,只是为了重申其他答案,您可以在此示例中使用string.Concat("string", null)

您正尝试在null上执行ToString()方法。 您需要一个有效的对象才能执行方法。

.show函数必须具有空检查并处理它。

因为,第二个调用是期望“s”的对象满足ToString()方法请求。 因此,在调用.Show()之前,s.ToString()会在尝试调用方法时失败。

有趣的是,虽然.Show()是正确实现的,但是很多这样的方法都希望传入非null实例。通常,当你使用NullObject模式时,调用者不应该处理这种行为。

可能Show方法处理空值而只显示任何内容。 s – s.ToString()的第二次使用失败,因为您没有运行ToString方法。