Eri*_*ric 6 c# scope variable-names
可能重复:
子范围和CS0136
C#变量范围
虽然我已经使用C#很长一段时间了,但我偶然发现了这个错误.
如果我有以下内容:
if(true)
{
int x = 0;
}
int x = 0;
Run Code Online (Sandbox Code Playgroud)
我收到一条错误消息: A local variable named 'x' cannot be declared in this scope because it would give a different meaning to 'x', which is already used in a child scope to denote something else.
如果我这样做:
if(true)
{
int x = 0;
}
x = 0;
Run Code Online (Sandbox Code Playgroud)
我收到一条错误消息: The name 'x' does not exist in the current context.
我可以理解有一个或另一个,但为什么这两个错误都存在?第一种选择有没有办法?我觉得很烦人.
谢谢.
存在这两个错误是为了阻止您犯错误或导致您的同事想要杀死您.
第一个失败是因为一次在范围内有两个同名的局部变量令人困惑.
第二个失败,因为变量的范围是if语句,并且您尝试在该范围之外访问它.
如果你想要一个可以在块内外使用的单个变量,你只需要在块之前声明它:
int x;
if (true)
{
x = 0;
}
x = 0;
Run Code Online (Sandbox Code Playgroud)
如果你真的希望两个单独的变量同时在范围内(在块内),那么给它们不同的名称 - 从而避免以后混淆.
编辑:您可以在单个方法中声明具有相同名称的多个局部变量,但它们必须具有单独的范围.例如:
public void Foo(IEnumerable<string> values)
{
double sum = 0;
foreach (string x in values)
{
int z = x.Length;
sum += z;
}
foreach (string x in values)
{
double z = double.Parse(x);
sum += z;
}
}
Run Code Online (Sandbox Code Playgroud)
就个人而言,当变量具有有意义的名称和方法很短时,我不会经常使用这种能力 - 至少不会使用不同的类型.但它绝对合法,有时肯定会有用.
| 归档时间: |
|
| 查看次数: |
622 次 |
| 最近记录: |