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()&
基础教程推荐
- 创建属性设置器委托 2022-01-01
- C# - 如何列出发布到 ASPX 页面的变量名称和值 2022-01-01
- 使用 SED 在 XML 标签之间提取值 2022-01-01
- 从 VB6 迁移到 .NET/.NET Core 的最佳策略或工具 2022-01-01
- Page.OnAppearing 中的 Xamarin.Forms Page.DisplayAlert 2022-01-01
- 当键值未知时反序列化 JSON 2022-01-01
- 我什么时候应该使用 GC.SuppressFinalize()? 2022-01-01
- C# - 将浮点数转换为整数...并根据余数更改整数 2022-01-01
- 如何使用OpenXML SDK将Excel转换为CSV? 2022-01-01
- 覆盖 Json.Net 中的默认原始类型处理 2022-01-01