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并打印出空消息框.
由于这个问题在Google上搜索"c#toString null"的排名很高,我想补充说该Convert.ToString(null)方法会返回一个空字符串.
但是,只是为了重申其他答案,您可以string.Concat("string", null)在此示例中使用.
小智 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)
| 归档时间: |
|
| 查看次数: |
56425 次 |
| 最近记录: |