c#: List<T>是地址型变量

List<T> 被声明为class, 所以它是地址型变量。而值型变量会被声明为struct。

在赋值时需要注意,比如:

List<int> listA = new List<int>(){1, 2, 3};
List<int> listB = new List<int>();
List<int> listC = new List<int>();

listB = listA;
listC = listA;

for(int i = 0; i< listB.Count; i++)
{
    listB[i] =listC[i] *2;
    Console.WriteLine(listB[i] + "::" +listC[i]);
       
}

/*output:
2::2
4::4
6::6
*/

 

从上例可以看出,将listA的值赋给listB和listC后,当改变listB的值时,listA和listC的值也随之改变。

 

如果想取消之间的关联性,可将listA的每个值直接添加到listB和listC中。

List<int> listA = new List<int>(){1, 2, 3};
List<int> listB = new List<int>();
List<int> listC = new List<int>();

//just passing the value in listA to listB and listC
listB = listA.GetRange(0, listA.Count);
listC = listA.GetRange(0, listA.Count);for(int i = 0; i< listB.Count; i++)
{
    listB[i] =listC[i] *2;
    Console.WriteLine(listB[i] + "::" +listC[i]);
       
}

/*output:
2::1
4::2
6::3
*/

 

posted @ 2012-12-31 13:27  马语者  阅读(1175)  评论(0编辑  收藏  举报