谁能解释为什么给定以下代码我可以访问myInt但不能访问myInt2?
if(int.TryParse("10", out int myInt))
{
//Do Something
}
else if(int.TryParse("100", out int myInt2))
{
// Do Something else
}
System.Console.WriteLine(myInt);
System.Console.WriteLine(myInt2); //<-- Compile Error 'myInt2 doesnt exist in the current context
这是因为
:
if (condition)
{
// ...
}
else if (otherCondition)
{
// ...
}
相当于:
if (condition)
{
// ...
}
else
{
if (otherCondition)
{
// ...
}
}
现在您可以看到为什么范围不同了。第二个if
嵌套在else
块中。
请注意,在if
条件中引入的变量被引入到该if
的else
部分的作用域中,以及if
之后的作用域中 - 但是嵌套if
会将变量引入嵌套if
的作用域中,因此它对外部if
的作用域不可见。
(我查看了 C# 标准以为此提供参考,但我还没有找到一个好的参考。如果我这样做,我会更新这篇文章。
顺便说一下,这适用于多个 if/else,如下所示:
if (init(out int a))
{
// Can access 'a'here. Cannot access 'b' or 'c'.
}
else if (init(out int b))
{
// Can access 'a' and 'b' here. Cannot access 'c'.
}
else if (init(out int c))
{
// Can access 'a', 'b' and 'c' here.
}
// Cannot access 'b' or 'c' here.
在逻辑上与以下内容相同:
if (init(out int a))
{
// Can access 'a' here. Cannot access 'b' or 'c'.
}
else
{
if (init(out int b))
{
// Can access 'a' and 'b' here. Cannot access 'c'.
}
else
{
if (init(out int c))
{
// Can access 'a', 'b' and 'c' here.
}
}
// Cannot access 'c' here.
}
// Cannot access 'b' or 'c' here.
out int name
构造是简化代码编写的另一种方法。请记住,您在 C# 6 中发布的等效代码是:
int myInt
if(int.TryParse("10", out myInt))
{
//Do Something
}
else
{
int myInt2
if(int.TryParse("100", out myInt2))
{
// Do Something else
}
}
System.Console.WriteLine(myInt);
System.Console.WriteLine(myInt2); //<-- Compile Error 'myInt2 doesn't exists