2

我试图在 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();
}

一种或另一种方式,将创建 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();
}

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

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

4

3 回答 3

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
}

但是让我给你一些提示:

  • 不要投资太多ArrayList(),看看吧List<T>
  • 要非常小心你如何使用catch {}.
    出了点问题(非常),提供默认答案通常不是正确的策略。
于 2013-10-11T20:47:43.557 回答
0

尝试这个:

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.
   items = new ArrayList();
}
于 2013-10-11T20:51:27.093 回答
0

您不需要重新创建 items 变量,只需实例化它。

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.
    items = new ArrayList();
}
于 2013-10-11T20:49:48.240 回答