c# - 模式匹配 - if block 之外范围内的变量

标签 c# pattern-matching c#-7.0

我试图理解为什么 y 位于以下示例的范围内:

static void Main(string[] args)
{
    int x = 1;
    if (x is int y) { }

    Console.WriteLine("This should NOT be in scope:" + y); // but it is...
}

如果我将 int x 更改为 object x,则 y 不再在范围内(如预期)。

为什么当匹配的表达式为 int 类型时,y 在范围内,而当类型为 object 时,则不在范围内?奇怪的是,范围根据表达式类型而变化。

当表达式类型和模式类型相同并且它们都是值类型时,

y 似乎保留在范围内。 (当两种类型都是 DateTime 时,存在相同的问题,但当它们都是 string 时,则不存在)。

(csc 版本为 2.0.0.61213。)


更新:看起来y在这两种情况下都在范围内。在 object 情况下,编译器错误是“使用未分配的局部变量‘y’”。所以它不会提示变量超出范围。

最佳答案

问题在于创建的输出代码,这导致了这种奇怪的行为,在我看来这是一个错误。我想这个问题最终会得到解决。

事情是这样的:x is int y 在编译时计算结果为 true ,从而产生 if 已过时,并且在 if 之前完成赋值。 See the compiled code here :

int num = 1;
int num2 = num;
bool flag = true;
if (flag)
{
}
Console.WriteLine("This should NOT be in scope:" + num2);

is object 变体的编译中似乎存在错误。它编译成这样(注意我添加的括号):

int num = 1;
object arg;
bool flag = (arg = num as object) != null;

Console.WriteLine("This should NOT be in scope:" + arg);

即使在 C# 6 中,这也是有效的。但是,编译器认为 arg 并不总是被设置。添加 else 分支修复了此错误:

else { y = null; }

Results in :

int num = 1;
object arg;
bool flag = arg = num as object != null;
if (!flag)
{
    arg = null;
}
Console.WriteLine("This should NOT be in scope:" + arg);

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

相关文章:

c# - 使用元组作为接口(interface)通用的显式接口(interface)实现不起作用

C# 7 模式匹配

c# - NHibernate:具有通用枚举属性的映射类

c# - 如何以编程方式更改 Crystal Report 中文本对象的文本

c# - 属性和命名/可选构造函数参数不起作用

java - 如何在 java 中的 String 的 split() 中使用模式

javascript - 从数据表创建复杂的 json C#

Scala 中的正则表达式非捕获组

pattern-matching - 从 Rust 的比赛中提早突破

c# - 字符串上的模式匹配