我试图在 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{} block 中做任何事情,因为它说“它已经被创建了”。
我希望能够创建一个程序来记住它之前运行时的操作,但我似乎无法围绕正确的概念取得进展。
请您参考如下方法:
您必须将范围向外移动:
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 {}.
出了点(非常)错误,提供默认答案通常不是正确的策略。
