字符串未正确连接

时间:2019-10-28 10:44:20

标签: c#

我有以下代码,其中字符串不被串联

string postCode = "1245";
string city = "Stockholm";
string postCodeAndCity = postCode ?? " " + " " + city ?? " ";

我得到的输出为 1245 。不确定为什么不包括城市。

但这行有效

string.Concat(postCode??" ", " ", city?? " ");

那为什么第一种方法不起作用?

2 个答案:

答案 0 :(得分:7)

??运算符的关联如下:

string postCodeAndCity = postCode ?? (" " + " " + city ?? (" "));

因此,如果postCode不为null,则只需postCode。如果postCode为空,则需要(" " + " " + city ?? (" "))

您可以从precedence table看到这一点,其中??的优先级低于+。因此,+的绑定比??的绑定更紧密,即a ?? b + c的绑定为a ?? (b + c),而不是(a ?? b) + c

但是,在:

string.Concat(postCode??" ", " ", city?? " ");

逗号的优先级当然比??高。使用+的等效项是:

(postCode ?? " ") + " " + (city ?? " ");

我怀疑您可能想做的是:

  1. 如果postCodecity都不为空,则在两者之间留一个空格。
  2. 如果一个为空,但另一个不是,则取非空。
  3. 如果两者均为空,则输入一个空字符串。

您可以写这篇长篇文章:

if (postCode != null)
{
    if (city != null)
        return postCode + " " + city;
    else
        return city;
}
else
{
    if (postCode != null)
        return postCode;
    else
        return "";
}

您可以使用以下方法将其编写得更短(尽管价格稍贵):

string.Join(" ", new[] { postCode, city }.Where(x => x != null));

答案 1 :(得分:0)

您应该为此使用字符串插值:

var output = $"{postCode} {city}"

有关更多信息,请参见: https://docs.microsoft.com/de-de/dotnet/csharp/language-reference/tokens/interpolated