【发布时间】:2013-03-08 19:06:40
【问题描述】:
为什么aFooList 包含最后一项的五个副本,而不是我插入的五个项?
预期输出: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);
}
}
}
}
【问题讨论】:
-
您只创建了一个 foo 对象,并将其添加到列表中 5 次