我無法理解在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