我有这段代码,但我不明白为什么最后一行会给我一个警告,如果前两行没有:
[return: NotNull]
public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T>? sourceEnumerable) => sourceEnumerable ?? Array.Empty<T>();
public static void ConfigurationSectionTest(IConfigurationSection? cfg)
{
IEnumerable<IConfigurationSection>? myChildren = cfg?.GetChildren();
IEnumerable<IConfigurationSection> safeChildren = myChildren.EmptyIfNull();
IEnumerable<IConfigurationSection> safeChildren2 = cfg?.GetChildren().EmptyIfNull(); //Warning: Converting null literal or possible null value to non-nullable type.
}
这个:
cfg?.GetChildren().EmptyIfNull();
相当于
cfg is null ? null : cfg.GetChildren().EmptyIfNull();
查看 空条件运算符
?.
和 ?[]
的文档
:
空条件运算符是短路的。也就是说,如果条件成员或元素访问操作链中的一个操作返回
,则该链的其余部分不会执行。在以下示例中,如果null
计算为B
,则不计算A
;如果null
或C
计算为A
,则不计算B
:null
A?.B?.Do(C); A?.B?[C];
因此,如果
cfg?.GetChildren().EmptyIfNull();
为空,则 cfg
为空。
一种解决方法是使用括号:
IEnumerable<IConfigurationSection> safeChildren2 = (cfg?.GetChildren()).EmptyIfNull();