为什么加空为一个字符串是否合法? [英] Why is adding null to a string legal?

查看:150
本文介绍了为什么加空为一个字符串是否合法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

字符串基础MSDN文章显示这一点:

string str = "hello";
string nullStr = null;
string emptyStr = "";

string tempStr = str + nullStr; // tempStr = "hello"
bool b = (emptyStr == nullStr);// b = false;
string newStr = emptyStr + nullStr; // creates a new empty string
int len = nullStr.Length; // throws NullReferenceException

为什么不空串联抛出一个空引用异常?它是做程序员的生活更轻松,使得他们不必在连接前检查null?

Why doesn't concatenating with null throw a null reference exception? Is it to make a programmer's life easier, such that they don't have to check for null before concatenation?

推荐答案

在字符串连接操作,
  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.

如果一个
  字符串连接操作数是
  空,空字符串被替换。
  否则,任何非字符串参数是
  转换成字符串再presentation
  通过调用虚拟的ToString
  从object类型继承的方法。

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.

这篇关于为什么加空为一个字符串是否合法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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