是否可以在 C# 中使用 foreach 通过引用来迭代 int 数组

Bob*_*421 5 c#

是否可以在 C# foreach 循环中通过引用迭代 int 数组?

我的意思是这样的:

 int[] tab = new int[5];
 foreach (ref int i in tab)
 {
     i=5;
 }
Run Code Online (Sandbox Code Playgroud)

谢谢

Fab*_*jan 1

是否可以在 C# foreach 循环中通过引用迭代 int 数组?

不,foreachC# 中的循环并非旨在对其迭代的集合进行更改。它使用readonly不能用作赋值目标的局部变量。

您仍然可以使用for循环来做到这一点:

var list = new List<MyClass>();

for(var i = 0; i < list.Count; i++)
{
   list[i] = new MyClass();
}
Run Code Online (Sandbox Code Playgroud)

或者使用 LINQ :

list = list.Select(e => new MyClass()).ToList(); // note that this will create a copy of list
Run Code Online (Sandbox Code Playgroud)