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()&
基础教程推荐
- C# 9 新特性——record的相关总结 2023-04-03
- 将数据集转换为列表 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 如果条件可以为空 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
