[英]Concatenate nullable object with string
This:这个:
int? temp = 0;
return "123 " + temp ?? "null" + " 456";
returns 123 0
, but I expected: 123 0 456
返回
123 0
,但我预计: 123 0 456
This:这个:
int? temp = null;
return "123 " + temp ?? "null" + " 456";
returns 123
, but I expected: 123 null 456
返回
123
,但我期望: 123 null 456
How can I get expected results?我怎样才能得到预期的结果?
You need to change the precedence of the ??
您需要更改
??
operator.操作员。 Use
用
return "123 " + (temp?.ToString() ?? "null") + " 456";
Your current code does您当前的代码确实
int? temp = 0;
return "123 " + temp ?? ("null" + " 456");
Put it in different order:把它放在不同的顺序:
int? temp = 0;
return "123 " + (temp?.ToString() ?? "null") + " 456";
Or, in order to get rid of pesky +
:或者,为了摆脱讨厌的
+
:
return $"123 {temp?.ToString() ?? "null"} 456";
这里已经有这么多花哨的解决方案,我将添加一个简单的“老式时尚解决方案”:)
"123 " + (temp.HasValue ? temp.ToString() : "null") + " 456"
这是一种应该有效的编写方式:
$"123 {(temp == null ? "null" : temp.ToString())} 456"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.