为什么是有效的来连接空字符串,但不叫" null.ToString()"? [英] Why is it Valid to Concatenate Null Strings but not to Call "null.ToString()"?

查看:164
本文介绍了为什么是有效的来连接空字符串,但不叫" null.ToString()"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是合法的C#code

This is valid C# code

var bob = "abc" + null + null + null + "123";  // abc123

这是不是有效的C#code

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.

+二元运算的更多信息:

二元+运算符执行字符串连接时,一个或两个操作数为string类型。

The binary + operator performs string concatenation when one or both operands are of type string.

如果字符串连接的一个操作数为null,一个空字符串代替。否则,任何非字符串参数都通过调用虚拟的ToString 方法继承类型的对象转换为它的字符串重新presentation。

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 返回,一个空字符串代替。

If ToString returns null, an empty string is substituted.

在第二个错误的原因是:

空(C#参考) - 空关键字是一个文字,它重新presents空引用,一个不指向任何对象。空是引用类型变量的默认值。

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()"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆