可空引用类型在没有中间变量的情况下无法工作

问题描述 投票:0回答:2

我有这段代码,但我不明白为什么最后一行会给我一个警告,如果前两行没有:

    [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.
    }
c# nullable-reference-types
2个回答
1
投票

这个:

cfg?.GetChildren().EmptyIfNull();

相当于

cfg is null ? null : cfg.GetChildren().EmptyIfNull();

1
投票

查看 空条件运算符

?.
?[]
的文档 :

空条件运算符是短路的。也就是说,如果条件成员或元素访问操作链中的一个操作返回

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();
© www.soinside.com 2019 - 2024. All rights reserved.