c# - 字符串没有正确连接
问题描述
我有以下代码,其中字符串没有连接
string postCode = "1245";
string city = "Stockholm";
string postCodeAndCity = postCode ?? " " + " " + city ?? " ";
我得到的输出为1245。不知道为什么它不包括城市。
但是这条线有效
string.Concat(postCode??" ", " ", city?? " ");
那么为什么第一种方法不起作用?
解决方案
??
操作员关联如下:
string postCodeAndCity = postCode ?? (" " + " " + city ?? (" "));
所以如果postCode
不为空,它只需要postCode
. 如果postCode
为空,则需要(" " + " " + city ?? (" "))
.
您可以从优先级表中看到这一点,其中的??
优先级低于+
。因此+
比绑定更紧密??
,即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));
推荐阅读
- three.js - react-three/fiber 点击后台监听
- scala - 在 Sangria 运行时解析 GraphQL 接口的具体类型
- c++ - 编译器是否需要在基类中内联既是虚函数又是最终函数的函数?
- javascript - 为什么没有到达此元素的信息?
- css - CSS汉堡菜单不显示菜单
- android - 在 WiFi 热点 Android 7 Nougat 中获取 IP 地址时出错
- java - 尝试构建 nifi-maven 项目时出错
- sql - How to execute join between three slow change dimensions sort by all start date columns?
- xodus - 在 Xodus 数据库中最大化或强制进行完全垃圾收集
- php - 在 Blade 模板中的 Laravel 路由上使用 https