空字符串上的ToString [英] ToString on null string

查看:484
本文介绍了空字符串上的ToString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why does the second one of these produce an exception while the first one doesn't?

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

已更新-我能理解的一个例外是(对我来说)令人费解的一点是为什么第一部分没有没有表现出异常。如下图所示,这与消息框无关。

Updated - the exception I can understand, the puzzling bit (to me) is why the first part doesn't show an exception. This isn't anything to do with the Messagebox, as illustrated below.

例如:

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

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

The first part appears to be implicitly converting a null to a blank string.

推荐答案

因为不能在<$ c $上调用实例方法 ToString() c> null 参考。

because you cannot call instance method ToString() on a null reference.

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

And MessageBox.Show() is probably implemented to ignore null and print out empty message box.

这篇关于空字符串上的ToString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆