2012-07-28 38 views
-4

有什麼辦法可以在C#中執行以下操作嗎?c#對引用的引用

List<int> aList = new List<int>(); 
List<int> bList = new List<int>(); 
... // fill the list somehow 
List<int> referece; //????? 
if (doThis) 
    referece = aList; 
else 
    referece = bList; 

reference= .... assign another list to reference 

這是可能的C#?在C++中,我會參考一個列表,但在c#中?


編輯: 我改正了我的例子。思考是,我想用新的/不同的列表替換列表,並且我想更改aList或bList。 當我將一個新列表分配給引用時,aList和bList不會更改。但這就是我真正想要的,更改aList或bList。引用只是選擇包含列表的變量。

+4

如果'DoSomethingWithSelectedList'實際上是一個方法的所有方法,這將工作完全作爲編碼 – 2012-07-28 13:14:59

+0

什麼* *究竟你想去做? – 2012-07-28 13:22:15

回答

3

問題在哪裏?

List<int> aList = new List<int>(); 
List<int> bList = new List<int>(); 
... // fill the list somehow 
List<int> referece = null; 
if (doThis) 
    referece = aList; 
else 
    referece = bList; 

if(reference != null) 
    reference.DoSomethingWithSelectedList(); 

List<T>是類(refrence類型),所以List<T>類型的任何變量是refrence到List<T>類的對象。

+0

問題不是答案,問題是列表上沒有DoSomethingWithSelectedList 2012-07-28 13:12:14

+0

@PeterRitchie:你很快......列表上的DoSomethingWithSelectedList()與C++中的問題完全相同! – Mithrandir 2012-07-28 13:15:10

+0

DoSomethingWithSelectedList()是例如Clear(),AddRange()... 事情是,我希望aList或bList被更改。參考只是選擇我想要操作的列表。 – bebo 2012-07-28 13:34:20

1

List<int>的東西需要一個擴展方法象下面這樣:

public static void DoSomethingWithSelectedList(this List<int> myList) 
     { 
      // your code 
     } 

和列表是在C#中的引用類型。

0

您應該設計自己的列表,而不是從列表導出,但實現ICollection接口添加你需要