问题描述
这是有效的 C# 代码
This is valid C# code
var bob = "abc" + null + null + null + "123"; // abc123
这不是有效的 C# 代码
This is not valid C# code
var wtf = null.ToString(); // compiler error
为什么第一条语句有效?
Why is the first statement valid?
推荐答案
第一个工作的原因:
来自 MSDN:
在字符串连接操作中,C# 编译器将空字符串视为空字符串,但不会转换原始空字符串的值.
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.
有关的更多信息+ 二元运算符:
当一个或两个操作数都是字符串类型时,二元 + 运算符执行字符串连接.
The binary + operator performs string concatenation when one or both operands are of type string.
如果字符串连接的操作数为空,则替换为空字符串.否则,通过调用从类型对象继承的虚拟 ToString 方法,将任何非字符串参数转换为其字符串表示.
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.
如果 ToString 返回 null,则替换为空字符串.
If ToString returns null, an empty string is substituted.
第二个错误的原因是:
null(C# 参考) -null 关键字是表示空引用的文字,不引用任何对象.null 是引用类型变量的默认值.
null (C# Reference) - The null keyword is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables.