我正在使用 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'
我正在寻找一些博客,据说这会起作用。
我错过了什么吗?
执行此检查并将字符串加入一行的最佳替代方法是什么?
答案 0 :(得分:9)
由于类型必须匹配?? (null-coalescing)运算符的任一侧,您应该传递一个字符串数组,在这种情况下,您可以传递一个空字符串数组。
String keywords = String.Join(",", information?.Keywords ?? new string[0]);
答案 1 :(得分:1)
最好的选择是在加入字符串之前检查null :
var keywords = information?.Keywords == null ? "" : string.Join(",", information.Keywords);