【发布时间】:2015-01-26 23:35:03
【问题描述】:
我的理解是,您无法访问其范围之外的变量(通常从声明点开始,到声明它的同一块的大括号结束)。
现在考虑以下代码:
void SomeMethod()
{
try
{
// some code
}
catch (Exception ex)
{
string str = "blah blah"; // Error: Conflicting variable `str` is defined below
return str;
}
string str = "another blah"; // Error: A local variable named `str` cannot be defined in this scope because it would give a different meaning to `str`, which is already used in the parent or current scope to denote something else.
return str;
}
我把代码改成如下:
void SomeMethod()
{
try
{
// some code
}
catch (Exception ex)
{
string str = "blah blah";
return str;
}
str = "another blah"; // Error: Cannot resolve symbol 'str'
return str;
}
有什么解释为什么会这样吗?
【问题讨论】: