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{} 块中做任何事情,因为它说'它已经被创建了。
我希望能够创建一个程序来记住它之前运行时的操作,但我似乎无法在正确的概念上取得领先。
您将不得不向外移动范围:
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 {}.