我在下面复制了一个非常小的代码示例。在我的代码中,我明确检查 AboveValue
和 BelowValue
均不为空,这适用于 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/