C#中添加字符串+空不抛出一个错误? [英] C# adding string + null doesn't throw an error?
问题描述
作为一个程序员,我本来期望这抛出异常。有为什么把null作为你好的理由
As a programmer I would have expected this to throw an exception. Is there a reason why it treats null as ""?
string s = "hello";
string t = null;
Console.WriteLine(s + t);
输出:
Output:
您好
只是为了强调我的问题,你知道的为什么决定把空进了的String.Empty制作的?我期待一些字符串被添加,但有一个问题更靠后的地方不是它获取适当,它带回来空。 !问题置若罔闻
Just to emphasise my question, do you know why the decision to turn null into String.Empty was made? I was expecting some string to be added but there was a problem further back where it wasn't retrieving it properly and it came back with null. The problem went unnoticed!
下面就是为什么我认为它是坏的(为什么我很震惊地发现没有错误)伪代码:
Here's a pseudocode of why I think it is bad (and why I was shocked to discover no error):
您可以假设我重载的ToString提供有关他们的人或细节的名称。
You can assume I overloaded ToString to give the name of the person or details about them.
Person p = PersonDatabase.GetForName("Jimmy Gibbs");
Console.WriteLine("Name is: " + p.ToString());
抛出异常。
Throws an exception because p is null
String p = PersonDatabase.GetForName("Jimmy Gibbs").Name;
Console.WriteLine("Name is: " + p);
不抛出异常,即使p是空(它把它当作)。
Doesn't throw an exception, even though p is null (it treats it as "").
(如果你想成为挑剔,说我将无法得到Name为GetforName将是空的,认为它是这样的:)
(If you want to be picky and say I won't be able to get Name as GetforName will be null, think of it as this:)
String p = PersonDatabase.GetNameFromID(1234); // Returns a string or null if not found
Console.WriteLine("Name is: " + p);
(如果您在列表或数组使用这个值,你会用一个空白项结束了这是什么为我打破了,它是创造的JavaScript,并试图通过ID)
(If you use this value in a list or array you'll end up with a blank entry which is what broke for me, it was creating javascript and trying to get element by ID of "")
推荐答案
在<一个得到元素HREF =http://www.microsoft.com/downloads/en/details.aspx?FamilyID=DFBF523C-F98C-4804-AFBD-459E846B268E> C#语言规范:
7.8.4加法运算符
7.8.4 Addition operator
字符串连接:
字符串操作符+(字符串x,y字符串);
字符串运算符+(字符串x,对象Y);
字符串运算符+(对象x,y字符串);
string operator +(string x, string y); string operator +(string x, object y); string operator +(object x, string y);
二元+
运营商的这些重载执行字符串连接。
如果字符串连接
的操作数为空,空字符串是
取代。,否则,任何非字符串
参数转换成字符串通过调用虚拟
ToString方法
表示从类型
对象继承。如果ToString返回null,将
空字符串代替。
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.
这篇关于C#中添加字符串+空不抛出一个错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!