簡體   English   中英

在catch塊內部聲明的變量與在外部(在catch塊之后)聲明的變量沖突

[英]Variable declared inside catch block conflicts with variable declared outside (after catch block)

我的理解是,您無法訪問變量范圍之外的變量(變量通常從聲明點開始,並在聲明該變量的同一塊的結尾處結束)。

現在考慮以下代碼:

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

有什么解釋為什么會發生嗎?

正如您已經說過的:作用域內部的聲明僅對所述作用域有效。 如果在trycatch塊內聲明任何內容,則該內容僅在那里有效。 相比:

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

將導致完全相同的錯誤。

為了使代碼段正常工作,您需要在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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM