簡體   English   中英

用字符串連接可為空的對象

[英]Concatenate nullable object with string

這個:

int? temp = 0;
return "123 " + temp ?? "null" + " 456";

返回123 0 ,但我預計: 123 0 456

這個:

int? temp = null;
return "123 " + temp ?? "null" + " 456";

返回123 ,但我期望: 123 null 456

我怎樣才能得到預期的結果?

您需要更改?? 操作員。

return "123 " + (temp?.ToString() ?? "null") + " 456";

您當前的代碼確實

  int? temp = 0;
  return "123 " + temp ?? ("null" + " 456");

把它放在不同的順序:

  int? temp = 0;
  return "123 " + (temp?.ToString() ?? "null") + " 456";

或者,為了擺脫討厭的+

  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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM