模式匹配 - 在 if 块之外的范围内的变量 [英] Pattern matching - variable in scope outside if-block

查看:46
本文介绍了模式匹配 - 在 if 块之外的范围内的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解为什么 y 在以下示例中处于范围内:

I'm trying to understand why y is in scope in the following example:

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 不再在范围内(如预期).

If I change int x to object x, then y is no longer in scope (as expected).

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

Why is y in scope when the expression being matched is of int type and not when the type is object? It's odd that the scoping changes based on the expression type.

y 似乎留在范围内,并且它们都是值类型.(当两种类型都是 DateTime 时存在同样的问题,但当它们都是 string 时不存在).

y seems to stay in scope when the expression type and the pattern type are the same, and they're both value types. (Same issue exists when both types are DateTime, but doesn't exist when they're both string).

(csc 版本为 2.0.0.61213.)

(csc version is 2.0.0.61213.)

更新:看起来 y 在这两种情况下都在范围内.在 object 情况下,编译器错误是使用未分配的局部变量 'y'".所以它不会抱怨变量超出范围.

Update: It looks like y is in scope in both cases. In the object case, the compiler error is "Use of unassigned local variable 'y'." So it's not complaining about the variable being out of scope.

推荐答案

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

The problem is the output code created, which results in this strange behavior, which is a bug in my opinion. I guess this will be fixed eventually.

事情是这样的:x is int y 计算结果为 true 在编译时,导致 if 已过时,并且在 if 之前完成了分配.此处见编译的代码:

The thing is this: x is int y evaluates to true on compile time, resulting in the if rendered obsolete and the assignment done before the 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 变体的编译似乎存在错误.它编译成这样(注意我添加的括号):

There seems a bug in the compilation of the is object variant. It compiles to something like this (note the parenthesis I added):

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 分支修复了这个错误:

Which is valid, even in C# 6. However, the compiler thinks arg isn't always set. Adding an else branch fixes this bug:

else { y = null; }

结果:

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);

这篇关于模式匹配 - 在 if 块之外的范围内的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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