C#引用循环变量

Das*_*alo 7 c# reference

是否有可能在C#中出现类似以下内容

foreach (ref string var in arr) {
    var = "new value";
}
Run Code Online (Sandbox Code Playgroud)

以便将var变量视为参考并分配给var将改变数组元素?

Mar*_*ell 22

没有这样的构造来更新循环; 迭代器是只读的.例如,以下提供了一个完全有效的迭代器:

public IEnumerable<int> Get1Thru5() {
    yield return 1; yield return 2; yield return 3;
    yield return 4; yield return 5;
}
Run Code Online (Sandbox Code Playgroud)

它会如何更新?什么将它更新?

如果数据是数组/列表/等,那么类似于:

for(int i = 0 ; i < arr.Length ; i++) {
    arr[i] = "new value";
}
Run Code Online (Sandbox Code Playgroud)

或其他选项取决于特定容器.


更新; 在,一个扩展方法:

public static void UpdateAll<T>(this IList<T> list, Func<T, T> operation) {
    for (int i = 0; i < list.Count; i++) {
        list[i] = operation(list[i]);
    }
}
static void Main() {
    string[] arr = { "abc", "def", "ghi" };
    arr.UpdateAll(s => "new value");
    foreach (string s in arr) Console.WriteLine(s);
}
Run Code Online (Sandbox Code Playgroud)