2013-07-21 159 views
4

我一直想知道为什么你能为循环创建类SomeClass的”的新对象,但你不能在同一foreach loop。Foreach vs for循环在C#中。新对象的创建,可以在循环,但不可能在foreach循环

的例子是波纹管:

SomeClass[] N = new SomeClass[10]; 

foreach (SomeClass i in N) 
{ 
    i = new SomeClass(); // Cannot assign to 'i' because it is a 'foreach iteration variable' 
} 

for (int i = 0; i < N.Length; i++) 
{ 
    N[i] = new SomeClass(); // this is ok 
} 

谁能解释一下我这种情况?

+1

看到这个:http://msdn.microsoft.com/en-us/library/vstudio/ttw7t8t6.aspx – Ric

回答

3

超过IEnumerable的对象的foreach循环迭代..

内部上面的代码变得

using(var enumerator=N.GetEnumerator()) 
while(enumerator.MoveNext()) 
{ 
    enumerator.current=new SomeClass();//current is read only property so cant assign it 
} 

正如在评论上述current属性是只读财产IEnumerator ..所以你不能分配任何东西