えーと、これをどう表現するかはよくわかりませんが..
クラスの3つのインスタンスを含むyieldreturnを使用して作成されたIEnumerableがある場合、.First()を呼び出すと最初のインスタンスの「コピー」が返されるように見えるのはなぜですか?
次のコードを参照してください。
public class Thing
{
public bool Updated { get; set; }
public string Name { get; private set; }
public Thing(string name)
{
Name = name;
}
public override string ToString()
{
return string.Format("{0} updated {1} {2}", Name, Updated, GetHashCode());
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("IEnumerable<Thing>");
var enumerableThings = GetThings();
var firstThing = enumerableThings.First();
firstThing.Updated = true;
Console.WriteLine("Updated {0}", firstThing);
foreach (var t in enumerableThings)
Console.WriteLine(t);
Console.WriteLine("IList<Thing>");
var thingList = GetThings().ToList();
var thing1 = thingList.First();
thing1.Updated = true;
Console.WriteLine("Updated {0}", thing1);
foreach (var t in thingList)
Console.WriteLine(t);
Console.ReadLine();
}
private static IEnumerable<Thing> GetThings()
{
for (int i = 1; i <= 3; i++)
{
yield return new Thing(string.Format("thing {0}", i));
}
}
}
}
これを実行すると、次の出力が生成されます。
IEnumerable<Thing>
Updated thing 1 updated True 37121646
thing 1 updated False 45592480
thing 2 updated False 57352375
thing 3 updated False 2637164
IList<Thing>
Updated thing 1 updated True 41014879
thing 1 updated True 41014879
thing 2 updated False 3888474
thing 3 updated False 25209742
しかし、IListとIEnmerableは同じように動作し、次のように出力されると思います...
IEnumerable<Thing>
Updated thing 1 updated True 45592480
thing 1 updated False 45592480
thing 2 updated False 57352375
thing 3 updated False 2637164
IList<Thing>
Updated thing 1 updated True 41014879
thing 1 updated True 41014879
thing 2 updated False 3888474
thing 3 updated False 25209742
何が足りないの?