使用默认值在C#6中检查null

Mig*_*ura 2 c# c#-6.0

我正在使用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);
Run Code Online (Sandbox Code Playgroud)

我正在检查信息是否为空(在我的真实代码中它可以是).如果它是加入String.Empty,因为String.Join在尝试加入null时会出错.如果它不为null,则只需加入信息.关键词.

但是,我收到此错误:

Operator '??' cannot be applied to operands of type 'string[]' and 'string'
Run Code Online (Sandbox Code Playgroud)

我正在寻找几个博客,据说这会起作用.

我错过了什么吗?

检查并将字符串连接在一行中的最佳替代方法是什么?

Igo*_*gor 9

由于类型必须匹配在??的两边(null-coalescing)运算符你应该传递一个字符串数组,在这种情况下你可以传递一个空字符串数组.

String keywords = String.Join(",", information?.Keywords ?? new string[0]);
Run Code Online (Sandbox Code Playgroud)