【问题标题】:Variable declared inside catch block conflicts with variable declared outside (after catch block)在 catch 块内声明的变量与在 catch 块外声明的变量冲突(在 catch 块之后)
【发布时间】: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;
}

有什么解释为什么会这样吗?

【问题讨论】:

    标签: c# variables try-catch


    【解决方案1】:

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

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

    将导致完全相同的错误。

    为了让你的代码 sn-p 工作,你需要在try-catch-block 之外声明字符串:

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

    【讨论】:

    • 啊——我几乎同时意识到了这一点。谢谢你的回答:)
    猜你喜欢
    • 2014-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    相关资源
    最近更新 更多