gpt4 book ai didi

c# - 从 try{} catch{} 访问变量

转载 作者:太空宇宙 更新时间:2023-11-03 21:40:55 25 4
gpt4 key购买 nike

我试图在 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 {} .
    出了点(非常)错误,提供默认答案通常不是正确的策略。

关于c# - 从 try{} catch{} 访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19326956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com