C#对另一个列表元素的引用列表 [英] C# List of references to another list elements
问题描述
我想用对注释列表元素的引用来构建一个子列表(我只需要少数几个满足条件的元素).
I want to build a sublist with references to the elements of anoter list (i need few of them, that are meeting the conditions).
我该怎么做:
List<int> mainList = new List<int>();
List<int> subList = new List<int>();
mainList.Add(5);
subList.Add(mainList[0]); //case 1
//subList[0] = mainList[0]; //case 2
Console.WriteLine("{0}", mainList[0]);
Console.WriteLine("{0}", subList[0]);
subList[0]++;
Console.WriteLine("{0}", mainList[0]);
Console.WriteLine("{0}", subList[0]);
mainList[0]+=2;
Console.WriteLine("{0}", mainList[0]);
Console.WriteLine("{0}", subList[0]);
在第一种情况下,我得到的是副本而不是引用,因为控制台输出是:
In the first case i'm getting the copy instead of reference because the console output is:
5
5
5
6
7
6
在第二种情况下,我收到 ArgumentOutOfRangeException 因为 subList[0]
未初始化.那么,我该怎么办呢?
In the second case i'm getting ArgumentOutOfRangeException because subList[0]
is not initialized.
So, how can i do this?
另外,根据速度/内存使用情况,最好保留mainList的inedexe的 List< int>
而不是引用吗?
Also, according to speed/memory usage may be it's even better to keep List<int>
of inedexes of the mainList instead of references?
推荐答案
由于@ManIkWeet和@Florian,我找到了解决方案:
Thanks to @ManIkWeet and @Florian, i've found the solution:
public class TestClass{
public int value;
}
...
List<TestClass> mainList = new List<TestClass>();
List<TestClass> subList = new List<TestClass>();
mainList.Add(new TestClass { value = 5 });
subList.Add(mainList[0]);
Console.WriteLine("{0}", mainList[0].value);
Console.WriteLine("{0}", subList[0].value);
subList[0].value++;
Console.WriteLine("{0}", mainList[0].value);
Console.WriteLine("{0}", subList[0].value);
mainList[0].value+=2;
Console.WriteLine("{0}", mainList[0].value);
Console.WriteLine("{0}", subList[0].value);
输出为:
5
5
6
6
8
8
这篇关于C#对另一个列表元素的引用列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!