这是有效的 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
returnsnull
, an empty string is substituted.
第二个错误的原因是:
null (C# Reference) - null 关键字是表示空引用的文字,不引用任何对象。 null是引用类型变量的默认值。
关于c# - 为什么连接空字符串有效但调用 "null.ToString()"无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10814282/