合并null检查和模式匹配的'if'语句时出错 [英] Error combining 'if' statements that null-checks and Pattern Matches

查看:52
本文介绍了合并null检查和模式匹配的'if'语句时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下按预期工作:

dynamic foo = GetFoo();

if (foo != null)
{
    if (foo is Foo i)
    {
        Console.WriteLine(i.Bar);
    }
}

但是如果我像下面这样组合if语句:

but if I combine the if statements like so:

if (foo != null && foo is Foo i)
{
    Console.WriteLine(i.Bar);
}

然后我收到编译器警告

使用未分配的局部变量'i'

任何人都可以解释为什么会发生这种情况吗?

Can anyone explain why this happens?

推荐答案

看来这实际上不是编译器错误.

It would appear that this is not, in fact, a compiler error.

以前在此处报道为错误.

但是,它已被关闭(不是漏洞).原因是由于C#语言规范的这一部分(请注意:我在这里引用的是GitHub上的用户 gafter -这不是我本人的原始内容):

However, it has been closed as not a bug. The reason is because of this part of the C# language spec (note: I am quoting here from user gafter on GitHub - this is NOT original content from myself):

如果条件逻辑运算符的操作数的编译时类型为dynamic,则将动态绑定表达式(动态绑定).在这种情况下,表达式的编译时类型是动态的,并且下面描述的解析将在运行时使用具有编译时类型动态的那些操作数的运行时类型进行.

If an operand of a conditional logical operator has the compile-time type dynamic, then the expression is dynamically bound (Dynamic binding). In this case the compile-time type of the expression is dynamic, and the resolution described below will take place at run-time using the run-time type of those operands that have the compile-time type dynamic.

具体来说,&&该操作不是编译时布尔短路操作,因为它的右侧操作数是动态类型.

Specifically, the && operation is not a compile-time boolean short-circuiting operation because its right-hand operand is of type dynamic.

微妙的东西,正如DavidG所说的,另一个可能的原因是避免 dynamic !(我必须承认,我仍然没有完全确信它不是错误,但这只是我不理解我猜的一切...)

Subtle stuff, and as DavidG says above, another reason to avoid dynamic where possible! (And I must confess, I'm still not completely convinced it's not a bug, but that's just me not understanding everything I guess...)

这篇关于合并null检查和模式匹配的'if'语句时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆