重复列表< T> .Add(T项目)项目
问题描述:
为什么aFooList
包含最后一个项目的五个副本,而不是我插入的五个项目?
Why does aFooList
contain five copies of the last item, instead of the five items I inserted?
预期输出:01234
实际输出:44444
using System;
using System.Collections.Generic;
namespace myTestConsole {
public class foo {
public int bar;
}
class Program {
static void Main(string[] args) {
foo aFoo = new foo(); // Make a foo
List<foo> aFooList = new List<foo>(); // Make a foo list
for (int i = 0; i<5; i++) {
aFoo.bar = i;
aFooList.Add(aFoo);
}
for (int i = 0; i<5; i++) {
Console.Write(aFooList[i].bar);
}
}
}
}
答
您已添加同一项aFoo
5次.修改引用类型对象的内容时,您不会创建新副本,而是修改了同一对象.
You have added the same item, aFoo
, 5 times. When you modify contents of a reference-type object you don't create new copies, you modify the same object.