我尝试在我的 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/