gpt4 book ai didi

c# - 合并空检查和模式匹配的 'if'语句时出错

转载 作者:行者123 更新时间:2023-12-02 10:57:59 26 4
gpt4 key购买 nike

预期的工作如下:

dynamic foo = GetFoo();

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

但是如果我像这样结合if语句:
if (foo != null && foo is Foo i)
{
Console.WriteLine(i.Bar);
}

然后我收到一个编译器警告
Use of unassigned local variable 'i'
谁能解释为什么会这样?

最佳答案

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

先前已将其报告为bug here

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

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.



具体来说,&&操作不是编译时 bool(boolean) 短路操作,因为它的右侧操作数是动态类型。

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

关于c# - 合并空检查和模式匹配的 'if'语句时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55157023/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com