Why is it Valid to Concatenate Null Strings but not to Call quot;null.ToString()quot;?(为什么连接空字符串有效但调用“null.ToString()无效?)
问题描述
这是有效的 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.
这篇关于为什么连接空字符串有效但调用“null.ToString()"无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么连接空字符串有效但调用“null.ToString()&
基础教程推荐
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
