-4

有没有办法在 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

3 回答 3

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>是 class (引用类型),因此任何类型的变量List<T>都是对 class 对象的引用List<T>

于 2012-07-28T13:09:49.027 回答
1

您需要一个扩展方法,List<int>如下所示:

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

List 是 c# 中的引用类型。

于 2012-07-28T13:16:59.250 回答
0

您应该设计自己的列表,而不是从 List 派生,而是实现 ICollection 接口添加您需要的所有方法

于 2012-07-28T13:24:56.707 回答