2016-11-17 21 views
-1

我發現,施工C#方法進行參數列表初始化不工作與Clear()

Method(out List<T>list) 
{ 
    list.Clear();  // doesn't allowed to initialyze List<T>list 
    list = null;  // is accepted by VSTO, however, is not so good 
} 

任何建議嗎?

+3

'out'參數通常用於在方法中創建的事物,而不用於修改傳入INTO HOD。也許你應該使用'ref'。您需要顯示將使用此代碼的上下文。 –

+0

謝謝Mattew!實際上,我正在處理該類中的列表字段的方法,如 public List str = new List (); ... –

回答

3

使用此方法不能使用未分配的參數。有一個簡單的規則:使用out如果您將初始化的參數傳遞給method,參數是否未初始化或使用ref

此代碼將正常運行:

void Method<T>(ref List<T> list) 
{ 
    list.Clear(); 
    list = null; 
} 

瞭解更多關於differencies這樣一個問題:What's the difference between the 'ref' and 'out' keywords?

2

如果你想使用out語義,不ref,你必須初始化列表:

Method(out List<T>list) 
{ 
    list = new List<T>(); 
}