首页 > 解决方案 > 字符串没有正确连接

问题描述

我有以下代码,其中字符串没有连接

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

我得到的输出为1245。不知道为什么它不包括城市。

但是这条线有效

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

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

标签: c#

解决方案


??操作员关联如下:

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

所以如果postCode不为空,它只需要postCode. 如果postCode为空,则需要(" " + " " + city ?? (" ")).

您可以从优先级表中看到这一点,其中的??优先级低于+。因此+比绑定更紧密??,即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));

推荐阅读