c# - 为什么连接空字符串有效但调用 "null.ToString()"无效?

标签 c# .net string null

这是有效的 C# 代码

var bob = "abc" + null + null + null + "123";  // abc123

这不是有效的 C# 代码

var wtf = null.ToString(); // compiler error

为什么第一个语句有效?

最佳答案

第一个工作的原因:

来自 MSDN :

In string concatenation operations,the C# compiler treats a null string the same as an empty string, but it does not convert the value of the original null string.

有关 + binary operator 的更多信息:

The binary + operator performs string concatenation when one or both operands are of type string.

If an operand of string concatenation is null, an empty string is substituted. Otherwise, any non-string argument is converted to its string representation by invoking the virtual ToString method inherited from type object.

If ToString returns null, an empty string is substituted.

第二个错误的原因是:

null (C# Reference) - null 关键字是表示空引用的文字,不引用任何对象。 null是引用类型变量的默认值。

关于c# - 为什么连接空字符串有效但调用 "null.ToString()"无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10814282/

相关文章:

swift - 为什么带有范围的 swift 子字符串需要特殊类型的 Range

c# - 具有随机 ID 的虚拟存储库数据外键

c# - 如何简化行进方 block 网格?

c# - 如何从 UpdatePanel 中的按钮强制执行完整的回发?

.net - 为按钮使用 StyleSelector

c# - 如何使用 .Net 获取符号链接(symbolic link)(或重解析点)的目标?

c# - 在下一个大写字母之前获取字符串(文本)

c# - 字符串变量的值无法转换为整数

c# - 一区多格

c++ - 优化静态字符串的字符串存储