어, 아주 확실하지 않은 방법으로 표현이 있지만 열거의 첫 번째 항목의 복사본을 반환 나타납니다 ..왜 감안할 때 Enumerable.First()
를 호출 않는 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
내가 무엇을 놓치고?!
Dan Bryant 대답은 정확한 용어로 기술 부분을 더 잘 다룹니다.:) –
물론, 이런, 고마워. - 고마워. – sackoverflow