c# - 模式匹配条件确保两个属性都不为空,但编译器会发出可能为空引用的警告。为什么?

标签 c# .net-core language-lawyer .net-6.0 c#-10.0

我在下面复制了一个非常小的代码示例。在我的代码中,我明确检查 AboveValueBelowValue 均不为空,这适用于 BelowValue (无警告),但不适用于 AboveValue(可能为空引用的警告)。考虑到我的条件,我不明白编译器如何想象 AboveValue 在代码中的此时可以为 null。

请注意,AboveValue 是基本接口(interface)的一部分,对于重现该问题至关重要 - 如果两个属性都在 IBelow 接口(interface)中,则代码不会显示任何警告,如果两个属性都在 IBelow 接口(interface)中,则显示两个警告IAbove 界面。

Console.WriteLine("Code needed to build the project");


public interface IAbove
{
    string? AboveValue { get; }
}

public interface IBelow : IAbove
{
    string? BelowValue { get; }
}

public class Test
{
    public static void Execute(IAbove above)
    {
        if (above is IBelow { AboveValue: not null, BelowValue: not null } belowTest1)
        {
            // warning CS8602: Dereferencing of a possible null reference
            Console.WriteLine(belowTest1.AboveValue.Length);
            // ok
            Console.WriteLine(belowTest1.BelowValue.Length);
        }
        if (above is not IBelow { AboveValue: not null, BelowValue: not null } belowTest2)
        {
            return;
        }
        // warning CS8602: Dereferencing of a possible null reference
        Console.WriteLine(belowTest2.AboveValue.Length);
        // ok
        Console.WriteLine(belowTest2.BelowValue.Length);
    }
}

最佳答案

我认为this generated code解释了问题,该模式被转换为以下代码。

IBelow below = above as IBelow;
if (below != null && above.AboveValue != null && below.BelowValue != null)

编译器(不够智能?)认为 AboveValue 属于 above,因此它只确定 above.AboveValue 不为 null。如果above的类型不是IAbove,例如上面的对象,然后检查belowTest1.AboveValue != null

关于c# - 模式匹配条件确保两个属性都不为空,但编译器会发出可能为空引用的警告。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74369516/

相关文章:

c# - ExecuteNonQuery 需要一个打开且可用的连接。连接的当前状态是关闭的

asp.net-core - 在 ASP.NET Core 应用程序中使用多个 HttpClient 对象

c++ - namespace 标识符的范围是什么?

c++ - 非类型模板参数的类型转换无效

c# - 如何关闭编码到 Form1 中的登录表单然后显示另一个表单?

C#访问内存映射文件

c# - 除非您先更改选择,否则 ComboBox 不会更新其显示列表

c# - 获取当前操作的完整路径

linux - 无法在某些目录下运行 dotnet?

c++ - 静态和动态模板初始化可以交错吗?