2010-06-03 16 views
2

我做这样的事情,并集合中的值不会更改为什么我不能编辑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}; 
       } 
+0

IsEqualTo()?尝试使用Equals()。 – tgiphil 2010-06-03 09:00:21

+0

@tgiphil对不起,这是我自己的扩展,它有 – Omu 2010-06-03 09:02:13

回答

7

如果将var source = GetFoos();更改为var source = GetFoos().ToList();,则会立即(并全部)读取列表。那么你应该能够改变这些值。

不要忘记存储更改的值,否则它们会在下次读取时恢复。

10

那是因为你创建新实例每次枚举GetFoos时间。

+0

内的Assert.AreEqual,你会如何解决这个问题? – Omu 2010-06-03 08:58:32

+0

将它们存储在函数的范围之外? – RvdK 2010-06-03 09:01:41

+0

@omu我要么去恐惧黑社会的解决方案,要么你接受的答案。 – SteinNorheim 2010-06-03 09:24:22

1

这是因为你使用了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 }, 
    }; 
} 
1

当你调用First()创建一个新的枚举。 因此GetFoos()被再次调用并返回一个新的对象。

相关问题