【问题标题】:Foreach vs for loop in C#. Creation of new object is possible in for loop, but not possible in foreach loopC# 中的 Foreach 与 for 循环。在 for 循环中可以创建新对象,但在 foreach 循环中不可能
【发布时间】:2013-07-20 11:01:41
【问题描述】:

我一直想知道为什么你可以在 for 循环中创建类 'SomeClass' 的新对象,而在 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
}

谁能解释一下这个场景?

【问题讨论】:

标签: c# for-loop foreach


【解决方案1】:

Foreach 循环遍历 IEnumerable 对象..

上面的代码在内部变成了

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

如评论current 中所述,属性是IEnumerator..的只读属性。所以你不能给它分配任何东西

【讨论】:

    【解决方案2】:

    foreach 迭代循环称为“只读上下文”。您不能在只读上下文中分配给变量。

    欲了解更多信息:http://msdn.microsoft.com/en-us/library/369xac69.aspx

    【讨论】:

      猜你喜欢
      • 2020-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-10
      • 2018-01-14
      • 2014-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多