簡體   English   中英

使用默認值在C#6中檢查null

[英]Check null in C# 6 with default value

我正在使用C#6 ,我有以下內容:

public class Information {
  public String[] Keywords { get; set; }
}

Information information = new Information {
  Keywords = new String[] { "A", "B" };
}

String keywords = String.Join(",", information?.Keywords ?? String.Empty);

我正在檢查信息是否為空(在我的真實代碼中它可以是)。 如果它是加入String.Empty,因為String.Join在嘗試加入null時會出錯。 如果它不為null,則只需加入信息。關鍵詞。

但是,我收到此錯誤:

Operator '??' cannot be applied to operands of type 'string[]' and 'string'

我正在尋找幾個博客,據說這會起作用。

我錯過了什么嗎?

檢查並將字符串連接在一行中的最佳替代方法是什么?

由於類型必須匹配在??的兩邊 (null-coalescing)運算符你應該傳遞一個字符串數組,在這種情況下你可以傳遞一個空字符串數組。

String keywords = String.Join(",", information?.Keywords ?? new string[0]);

最好的替代方法是加入字符串之前檢查null:

var keywords = information?.Keywords == null ? "" : string.Join(",", information.Keywords);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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