java - 使用 java 将增强 for 循环转换为 c# 时出错

标签 java c# for-loop

我尝试在我的 C# 代码中增强 Java 代码的 for 循环:

for (float value : array) {
    if (Float.isInfinite(value) || Float.isNaN(value)) {
        value = 0;
    }
}

我尝试过这个:

foreach (float value in array)
{
    if (float.IsInfinity(value) || float.IsNaN(value))
    {
        value = 0;
    }
}

但是我有这个错误,告诉我我无权修改值,因为它是迭代变量。

最佳答案

如果要更新迭代器变量,则需要使用普通的 for 循环:

for(int i = 0 ; i < array.Length; i++)
{

    if (float.IsInfinity(array[i]) || float.IsNaN(array[i]))
    {
        array[i] = 0;
    }
}

来自 C# 规范:

The iteration variable corresponds to a read-only local variable with a scope that extends over the embedded statement. During execution of a foreach statement, the iteration variable represents the collection element for which an iteration is currently being performed. A compile-time error occurs if the embedded statement attempts to modify the iteration variable (via assignment or the ++ and -- operators) or pass the iteration variable as a ref or out parameter.

关于java - 使用 java 将增强 for 循环转换为 c# 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38305855/

相关文章:

java - 打印不带括号和逗号的数组

javascript - Ajax 成功响应警报不起作用 C#

c# - LINQ To SQL 忽略唯一约束异常并继续

c++ - For循环间隔

c# - 如何将此循环写成一行?

java - 如何使用 Java Swing 布局整齐地缩进一些组件

java - "PKIX path building failed"和 "unable to find valid certification path to requested target"

java - Java 对象的最具体的子类?

c# - "private"修饰符有什么作用?

java - 切换数字的简单程序