我有以下代码,其中字符串不被串联
string postCode = "1245";
string city = "Stockholm";
string postCodeAndCity = postCode ?? " " + " " + city ?? " ";
我得到的输出为 1245 。不确定为什么不包括城市。
但这行有效
string.Concat(postCode??" ", " ", city?? " ");
那为什么第一种方法不起作用?
答案 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 ?? " ");
我怀疑您可能想做的是:
postCode
和city
都不为空,则在两者之间留一个空格。您可以写这篇长篇文章:
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