【发布时间】:2014-10-29 07:01:12
【问题描述】:
c#-6.0 中的 Null propagating operator / Conditional access expression 看起来是一个非常方便的功能。但我很好奇它是否有助于解决检查子成员是否不为空的问题,然后在 if 块内对所述子成员调用布尔方法:
public class Container<int>{
IEnumerable<int> Objects {get;set;}
}
public Container BuildContainer()
{
var c = new Container();
if (/* Some Random Condition */)
c.Objects = new List<int>{1,2,4};
}
public void Test()
{
var c = BuildContainer();
//Old way
if ( null != c && null != c.Objects && c.Objects.Any())
Console.Write("Container has items!");
//C# 6 way?
if (c?.Object?.Any())
Console.Write("Container has items!");
}
c?.Object?.Any() 会编译吗?如果传播运算符短路(我认为这是正确的术语)为空,那么您有if (null),这是无效的。
C# 团队会解决这个问题,还是我错过了 null 传播运算符的预期用例?
【问题讨论】:
标签: c#-6.0 c# null language-features c#-6.0