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