我试图理解为什么 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; }
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/