我试图在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{} 块中做任何事情,因为它说'它已经被创建。
我希望能够创建一个程序来记住以前运行时的操作,但我似乎无法围绕正确的概念取得进展。
您必须将范围向外移动:
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 {}
。
有些事情(非常)出错,提供默认答案通常不是正确的策略。
您不需要重新创建 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();
}
试试这个:
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();
}