从 try{} catch{} 访问变量

ATC*_*ger 2 c# scope try-catch

我试图在 try{} catch{} 方法之后访问一个变量(特别是一个 ArrayList)。

try 
{
//Here I would import data from an ArrayList if it was already created.
}
catch
{  
//Create new array list if it couldn't find one.
ArrayList items = new ArrayList();
}
Run Code Online (Sandbox Code Playgroud)

以一种或另一种方式,将创建 ArrayList 项目,我希望能够访问它。我之前尝试初始化 ArrayList ,如下所示:

ArrayList items;
try 
{
//Here I would import data from an ArrayList if it was already created.
}
catch
{  
//Create new array list if it couldn't find one.
ArrayList items = new ArrayList();
}
Run Code Online (Sandbox Code Playgroud)

但是我无法在 try{} catch{} 块中做任何事情,因为它说'它已经被创建了。

我希望能够创建一个程序来记住它之前运行时的操作,但我似乎无法在正确的概念上取得领先。

Hen*_*man 6

您将不得不向外移动范围:

ArrayList items;    // do not initialize
try 
{
   //Here I would import data from an ArrayList if it was already created.
   items = ...;
}
catch
{  
  //Create new array list if it couldn't find one.
  items = new ArrayList();  // note no re-declaration, just an assignment
}
Run Code Online (Sandbox Code Playgroud)

但是让我给你一些提示:

  • 不要投入太多,多ArrayList()看看List<T>
  • 非常小心你如何使用catch {}.
    出现了(非常)错误的情况,提供默认答案通常不是正确的策略。