在C#中附加到空字符串如何工作? [英] How does appending to a null string work in C#?
问题描述
我很惊讶地看到一个示例,该示例将字符串初始化为null,然后在生产环境中附加了一些内容.只是闻错了.
I was surprised to see an example of a string being initialised to null and then having something appended to it in a production environment. It just smelt wrong.
我确定它会抛出一个空对象异常,但是这个大大简化的示例也可以工作:
I was sure it would have thrown a null object exception but this greatly reduced example also works:
string sample = null;
sample += "test";
// sample equals "test"
* 请注意,我发现的原始代码将字符串属性设置为null并将其附加到其他位置,因此涉及编译器在编译时优化null的答案是无关紧要的.
有人可以解释为什么这样做没有错误吗?
Can someone explain why this works without error?
基于Leppie的回答,我使用了Reflector来查看string.Concat中的内容.现在真的很清楚为什么会发生这种转换(一点也不神奇):
Based on Leppie's answer I used Reflector to see what is inside string.Concat. It is now really obvious why that conversion takes place (no magic at all):
public static string Concat(string str0, string str1)
{
if (IsNullOrEmpty(str0))
{
if (IsNullOrEmpty(str1))
{
return Empty;
}
return str1;
}
if (IsNullOrEmpty(str1))
{
return str0;
}
int length = str0.Length;
string dest = FastAllocateString(length + str1.Length);
FillStringChecked(dest, 0, str0);
FillStringChecked(dest, length, str1);
return dest;
}
** 注意:我正在研究的特定实现(在Microsoft .Net库中)不会像C#标准和大多数答案所建议的那样转换为空字符串,而是使用一些测试来简化过程.最终结果与完成的结果相同,但是您可以:)
推荐答案
用于字符串的 +
运算符只是 string.Concat
的简写,它只是将 null
在连接之前将参数转换为空字符串.
the +
operator for strings are just shorthand for string.Concat
which simply turns null
arguments into empty strings before the concatenation.
更新:
string.Concat的通用版本:
The generalized version of string.Concat:
public static string Concat(params string[] values)
{
int num = 0;
if (values == null)
{
throw new ArgumentNullException("values");
}
string[] array = new string[values.Length];
for (int i = 0; i < values.Length; i++)
{
string text = values[i];
array[i] = ((text == null) ? string.Empty : text);
num += array[i].Length;
if (num < 0)
{
throw new OutOfMemoryException();
}
}
return string.ConcatArray(array, num);
}
这篇关于在C#中附加到空字符串如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!