![](/img/trans.png)
[英]Why can't I change elements from a linq IEnumerable in a for loop?
[英]Why can't I edit elements of 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};
}
这是因为每次枚举GetFoos时都会创建新实例。
如果你改变了var source = GetFoos();
into var source = GetFoos().ToList();
,列表立即(和完整)读取。 然后你应该能够改变价值观。
不要忘记存储更改的值,否则它们会在您下次阅读时还原。
这是因为你使用了yield return
。
你可以写:
public IEnumerable<Foo> GetFoos()
{
return new List<Foo>
{
new Foo { One = "1", Two = "2", Three = true },
new Foo { One = "1", Two = "2", Three = true },
new Foo { One = "1", Two = "2", Three = true },
};
}
当您调用First()
会创建一个新的枚举器。 因此再次调用GetFoos()
并返回一个新对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.