2013-10-11 127 views
0

嘗試在嘗試{} catch {}方法後訪問變量(特別是ArrayList)。嘗試訪問變量{} catch {}

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 {}趕上因爲它說,它已經被創建做什麼{}塊。

我希望能夠創建一個程序,以記錄從運行之前的行爲,但我似乎無法讓我的前方圍繞正確的概念。

+1

單從Catch塊 –

+0

刪除 'ArrayList的' 僅供參考,除非你使用.NET 2.0,你不應該使用'ArrayList'。您應該使用'List '代替。 –

+0

我建議你使用List 而不是ArrayList – Swag

回答

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 {}
    有些事情發生了(非常)錯誤,提供默認答案通常不是正確的策略。
+0

是對的,; = null?甜。現在我可以起來一個人 –

+0

是的!非常感謝你的幫助。將ArrayList設置爲null,然後只需調整try {} catch {}塊中的'items'ArrayList即可完美解決問題! ArrayList items = null; 我想你忘了刪除;後物品。謝謝。 – ATCraiger

+0

最好不要使用'= null;'在這裏,它只會掩蓋錯誤(忘記將它設置在正確的位置)。 '未分配的變量'錯誤是朋友,而不是敵人。 –

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(); 
} 
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(); 
}