[英]Why can't I edit elements of IEnumerable?
I do something like this and the value in the collection doesn't change 我做这样的事情,集合中的价值不会改变
[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时都会创建新实例。
If you change the var source = GetFoos();
如果你改变了var source = GetFoos();
into var source = GetFoos().ToList();
into var source = GetFoos().ToList();
, the list is read immediately (and in full). ,列表立即(和完整)读取。 Then you should be able to change the values. 然后你应该能够改变价值观。
Don't forget to store the changed values or else they revert the next time you read them. 不要忘记存储更改的值,否则它们会在您下次阅读时还原。
It is because of your use of yield return
. 这是因为你使用了yield return
。
You could write instead: 你可以写:
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 },
};
}
When you call First()
a new Enumerator is created. 当您调用First()
会创建一个新的枚举器。 So GetFoos()
is called again and return a new object. 因此再次调用GetFoos()
并返回一个新对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.