为什么我不能编辑IEnumerable的元素?

Omu*_*Omu 2 c# ienumerable

我做这样的事情,集合中的价值不会改变

                [Test]
                public void EnumerableTest()
                {
                    var source = GetFoos();

                    source.First().One = "hello";

                    Assert.AreEqual(source.First().One, "hello");
    //it fails

                }

//I actually return this from a repository
                public IEnumerable<Foo> GetFoos()
                {
                    yield return new Foo() {One = "1", Two = "2", Three = true};
                    yield return new Foo() {One = "1", Two = "2", Three = true};
                    yield return new Foo() {One = "1", Two = "2", Three = true};
                }
Run Code Online (Sandbox Code Playgroud)

Ste*_*eim 10

这是因为每次枚举GetFoos时都会创建新实例.


Han*_*ing 7

如果您更改var source = GetFoos();var source = GetFoos().ToList();,则立即(并完整)读取列表.然后你应该能够改变价值观.

不要忘记存储更改的值,否则它们会在您下次阅读时还原.