繁体   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