在catch块内声明的变量与在外部声明的变量冲突(在catch块之后)

时间:2014-11-28 10:17:32

标签: c# variables try-catch

我的理解是你不能访问其范围之外的变量(通常从声明点开始,并以声明它的同一块的大括号结束)。

现在考虑以下代码:

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

有没有解释为什么会发生这种情况?

1 个答案:

答案 0 :(得分:3)

正如您已经说过:范围内的声明仅对所述范围有效。如果您在trycatch块中声明了任何内容,那么它只会在那里有效。比较:

try
{
    string test = "Some string";
}
catch
{
    test = "Some other string";
}

将导致完全相同的错误。

要让您的代码段有效,您需要在try-catch - 块之外声明字符串:

void SomeMethod()
{
   string str = String.Empty;
   try
   {
      // some code
   }
   catch (Exception ex)
   {
      str = "blah blah";
      return str;
   }

   str = "another blah";
   return str;
}