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()&


- 在 LINQ to SQL 中使用 contains() 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 使用 rss + c# 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01