gpt4 book ai didi

c# - 模式匹配变量范围

转载 作者:可可西里 更新时间:2023-11-01 09:08:47 26 4
gpt4 key购买 nike

Roslyn Pattern Matching spec它指出:

The scope of a pattern variable is as follows:

If the pattern appears in the condition of an if statement, its scope is the condition and controlled statement of the if statement, but not its else clause.

不过最新的微软“What's new”postspresentations正在展示这个例子:

public void PrintStars(object o)
{
if (o is null) return; // constant pattern "null"
if (!(o is int i)) return; // type pattern "int i"
WriteLine(new string('*', i));
}

它显示了在模式匹配的 if 级别范围之外使用的模式匹配 i 变量。

这是疏忽,还是规范中的范围界定发生了变化?

最佳答案

来自同一文档:

the variables introduced by a pattern – are similar to the out variables described earlier

实际上这段代码:

if (!(o is int i)) return; // type pattern "int i"

或多或少等于:

int i;
if (!(SomeParsingOn(o, out i))) return; // type pattern "int i"

这意味着 i 声明在与 if 相同的级别,这意味着它不仅在 if 的范围内,但也适用于以下陈述。当您复制 if:

时可以看出这是真的
if (!(o is int i)) return; // type pattern "int i"
if (!(o is int i)) return; // type pattern "int i"

给出 错误 CS0128:一个名为“i”的局部变量已在此范围内定义

关于c# - 模式匹配变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40680781/

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