我Lists在C#中使用时遇到了一些令人困惑的行为.如果我添加一个集合(我既测试List<T>和Array给定类型的)到List(即List<List<int>>),修改的孩子List也将修改父的内容,List它被添加到.但是,如果我添加一个不是集合(即a bool或a int)List的对象,则修改对象本身不会修改List添加它的内容.我在下面提供了一些示例代码:
List<List<int>> intList = new List<List<int>>();
List<int> ints = new List<int>();
ints.Add(12345);
intList.Add(ints);
Console.WriteLine(intList[0].Count); //intList[0].Count is 1
ints.Clear();
Console.WriteLine(intList[0].Count); //intList[0].Count is 0
Run Code Online (Sandbox Code Playgroud)
看起来在上面的例子中,ints集合只是"映射"到了intList[0],所以当你修改ints集合本身时,你也在修改intList[0],因为它们是同一个对象.这与下一个例子形成对比:
List<bool> boolList = new List<bool>();
bool bigBool = false;
boolList.Add(bigBool);
Console.WriteLine(boolList[0]); //boolList[0] is false
bigBool = true;
Console.WriteLine(boolList[0]); //boolList[0] is...still false??
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,似乎不是映射到boolList[0],bigBool而是COPIED boolList[0].这boolList[0]是一个副本bigBool,它们是两个独立的对象.
所以我的问题是:为什么似乎有两个独立的功能List<T>.Add,取决于添加到什么类型List?我已经检查过MSDN,但我找不到任何提及此行为的内容.谢谢.