空字符串上的ToString

Mar*_*rtW 26 c# string null exception tostring

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

string s = null;
MessageBox.Show(s);
MessageBox.Show(s.ToString());
Run Code Online (Sandbox Code Playgroud)

更新 - 我能理解的异常,令人费解的一点(对我来说)是第一部分没有显示异常的原因.这与Messagebox没有任何关系,如下图所示.

例如:

string s = null, msg;
msg = "Message is " + s; //no error
msg = "Message is " + s.ToString(); //error
Run Code Online (Sandbox Code Playgroud)

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

Axa*_*dax 26

因为你不能ToString()null引用上 调用实例方法.

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

  • 第一位很好,但我认为我的问题的MessageBox位分散注意力,因此我的更新. (2认同)

Han*_*ant 13

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


Roo*_*lie 7

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

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

  • `Convert.ToString(null)` 返回一个 null 值,而不是空字符串(这可以通过调用 `Convert.ToString(null) == null` 来验证,它返回 `true`)。然而,传递一个 null *变量* 确实等于 null,因此 `object v = null; Convert.ToString(v) == string.Empty` 返回 true (请参阅此[answer](/sf/answers/1263723891/))。 (3认同)

小智 5

在你的后续问题/更新例如,在幕后调用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.
Run Code Online (Sandbox Code Playgroud)

  • 你能告诉我们*幕后*因为我肯定无法在mscorlib中找到它... (2认同)

Tom*_*ess 3

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