Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么不是';空字符串不是连接的标识吗?_C#_.net - Fatal编程技术网

C# 为什么不是';空字符串不是连接的标识吗?

C# 为什么不是';空字符串不是连接的标识吗?,c#,.net,C#,.net,我读了Eric Lippert的这篇博文,意识到空字符串不是C#中连接的标识。我没有遇到过让我意识到这是事实的情况,我总是认为这是一种身份。我想这是有原因的 string NullString = null; NullString = NullString + String.Empty; // results in and empty string, not null 结果是空字符串而不是null,这是什么原因?为什么字符串连接没有标识?这样做是为了方便还是实用?的文档解释了这种行为:

我读了Eric Lippert的这篇博文,意识到空字符串不是C#中连接的标识。我没有遇到过让我意识到这是事实的情况,我总是认为这是一种身份。我想这是有原因的

  string NullString = null;
  NullString = NullString + String.Empty; // results in and empty string, not null
结果是空字符串而不是
null
,这是什么原因?为什么字符串连接没有标识?这样做是为了方便还是实用?

的文档解释了这种行为:

使用空字符串代替任何空参数

基本上,
String.Concat
方法就是为了展示这种行为而设计的


这样做是为了方便还是实用


虽然只有框架设计团队可以直接回答这个问题,但这种行为确实有一些实际的好处。此行为允许您将字符串与
null
连接起来,而不创建
null
结果,这减少了大多数代码中所需的显式
null
检查的数量。如果没有这种行为,
someString+“abc”
将需要进行空检查,使用它时,可以保证非空值。

我必须承认我不理解“字符串连接的标识”。但是,
null+string.Empty
不是
null
而是
string.Empty
的原因是:

因为它是这样实现的

看看:

public static string Concat(string str0, string str1)
{
    if (string.IsNullOrEmpty(str0))
    {
        if (string.IsNullOrEmpty(str1))
        {
            return string.Empty;
        }
        return str1;
    }
    else
    {
        if (string.IsNullOrEmpty(str1))
        {
            return str0;
        }
        int length = str0.Length;
        string text = string.FastAllocateString(length + str1.Length);
        string.FillStringChecked(text, 0, str0);
        string.FillStringChecked(text, length, str1);
        return text;
    }
}
这也是:

该方法连接str0和str1;它不添加任何分隔符。 使用空字符串代替任何空参数


如果你问为什么。我想是因为这样更安全。如果您希望包含两个字符串,且其中一个字符串为空,为什么要选择
null
而不是
string.Empty

,因为它使用的是合同,其目的在中进行了描述

从String.Concat:

Contract.Ensures(Contract.Result<string>() != null);
Contract.Contract(Contract.Result()!=null);

请注意,
NullString+NullString
也会返回一个空字符串。

问题本质上是:它为什么会以这种方式设计、记录和实现?@delnan:我不知道,我认为这是因为获得一个空字符串而不是
null
更安全、更理想。编辑了我的答案。对于一般性问题“为什么它是以这种方式设计和实现的?”的答案通常是“因为替代方案更糟糕”@TimSchmelter“identity”意味着返回未更改的输入。它来自何处?为什么它被设计来展示这种行为,而不是在一个操作数为空字符串时返回另一个操作数不变的替代行为?@delnan这确实是没有人(可能是框架设计师除外)能够直接回答的问题。我怀疑这样设计是为了减少所需的空检查的数量,但这只是猜测,因为我不是框架设计团队的成员;)也许不能可靠地回答,但这毕竟是个问题。这不是第一个这样的问题。通常这些问题都能得到很好的回答,答案显示了现状如何比问题中的替代方案更好。