我无法理解在IEnumerable上调用ToArray()时会发生什么。我一直认为只有参考被复制。当在IEnumerable上调用ToArray()时会发生什么?
我希望这里的输出是: 真正 真正
而是我得到 真 假
这到底是怎么回事?
class One {
public bool Foo { get; set; }
}
class Two
{
public bool Foo { get; set; }
}
void Main()
{
var collection1 = new[] { new One(), new One() };
IEnumerable<Two> stuff = Convert(collection1);
var firstOne = stuff.First();
firstOne.Foo = true;
Console.WriteLine (firstOne.Foo);
var array = stuff.ToArray();
Console.WriteLine (array[0].Foo);
}
IEnumerable<Two> Convert(IEnumerable<One> col1) {
return
from c in col1
select new Two() {
Foo = c.Foo
};
}
他实际上只是在转换的列表上工作,在这种情况下,类One对它没有任何影响 – Rob 2011-01-10 02:00:45
@Rob:`One`是一个引用类型。在我的`Convert`版本中,没有`New One {..}`。它只是返回对同一个实例的引用。 – 2011-01-10 02:05:33