为什么将两个空字符串连接在一起结果是一个空字符串?

5

我尝试连接两个null字符串,结果很奇怪:返回一个空字符串!我想不出它是否有用或为什么会发生这种情况。

例如:

string sns = null;
sns = sns + sns;
// It results in a String.Empty

string snss = null;
snss = String.Concat(snss, snss);
// It results in a String.Empty too!

有人可以告诉我为什么它返回一个String.Empty而不是null吗?

1
+ 运算符是 String.Concat 方法的简写。如果传递的参数为 null,则将它们转换为空字符串。 - Raktim Biswas
我已经使用C#,C ++和C进行编程多年,直到今天才发现这个问题! 我以为如果所有参数都为空,则字符串连接将始终产生null。我以前怎么从来没有注意到这种行为呢?我现在感觉像一个新手。 - MikeTeeVee
2个回答

4

以下是C#语言规范中“7.8.4加法运算符”一节的片段:

String concatenation:

string operator +(string x, string y);
string operator +(string x, object y);
string operator +(object x, string y);

These overloads of the binary + operator perform string concatenation. 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. If ToString returns null, an empty string is substituted.


好发现,我能找到它 D=. - TheNoob
更多内容请参见谷歌图书 - Akira Yamamoto

2

2
看看第3002行就知道是谁给你踩了。=) - TheNoob
1
+只是使用Concat方法。https://dev59.com/aGkv5IYBdhLWcg3wzj41 - crthompson
@paqogomez 很好,谢谢你,我会查看那个SO问题的。 - TheNoob
谢谢您的澄清。不幸的是,我只能选择一个答案,但我已经给两个答案点赞了。生活不息,学习不止! - Striter Alfa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接