简体   繁体   English

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

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

I am using C# 6 and I have the following: 我正在使用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);

I am checking if information is null (in my real code it can be). 我正在检查信息是否为空(在我的真实代码中它可以是)。 If it is than join a String.Empty since String.Join gives an error when trying to join null. 如果它是加入String.Empty,因为String.Join在尝试加入null时会出错。 If it is not null then just join information.Keywords. 如果它不为null,则只需加入信息。关键词。

However, I get this error: 但是,我收到此错误:

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

I was looking on a few blogs and supposedly this would work. 我正在寻找几个博客,据说这会起作用。

Am I missing something? 我错过了什么吗?

What is the best alternative to do this check and join the string in one line? 检查并将字符串连接在一行中的最佳替代方法是什么?

As the types must match on either side of the ?? 由于类型必须匹配在??的两边 (null-coalescing) operator you should pass a string array, in this case you could pass an empty string array. (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