我有几个变量需要在 for 循环内分配。显然,当循环退出时,C# 会忽略其中发生的任何事情,并且变量将返回到其原始状态。具体来说,我需要它们成为列表的最后一个和倒数第二个元素。这是代码:

int temp1, temp2;
for (int i = 0; i < toReturn.Count; i++) {
     if (i == toReturn.Count - 2) { // Next-to-last element
         temp1 = toReturn[i];
     } else if (i == toReturn.Count - 1) { // Last element
         temp2 = toReturn[i];
     }
}
// At this point, temp1 and temp2 are treated as uninitialized

笔记:不要介意不好的变量名,它们实际上是临时变量。任何更复杂的事情都会让事情变得混乱。

现在,有两种方法(据我所知)可以解决这个问题:一种是弄清楚如何在循环退出后使变量生效,另一种是像在Python中那样做,你可以这样做 temp = my_list[-1] 获取列表的最后一个元素。这些在 C# 中是否可行?

编辑: 当我尝试编译时,出现“使用未分配的局部变量‘temp1’”错误。该代码甚至没有运行,它只是位于一个永远不会被调用的方法中。如果这有帮助,我将尝试在另一个循环中使用变量。

有帮助吗?

解决方案

为什么不干脆做...

int temp1 = 0;
int temp2 = 0;
    if (toReturn.Count > 1)
        temp1 = toReturn[toReturn.Count - 2];
    if (toReturn.Count > 0)
        temp2 = toReturn[toReturn.Count - 1];

其他提示

如果 toReturn.Count 为 0,则循环永远不会运行,并且 temp1 和 temp2 永远不会初始化。

这是做什么的?

if (toReturn.Count > 1) {
    temp1 = toReturn[toReturn.Count - 2]
    temp2 = toReturn[toReturn.Count - 1]
}

尝试给 temp1 和 temp2 一个初始值,即 0 或任何合适的值,因为它们可能永远不会被初始化

int temp1 = 0; // Or some other value. Perhaps -1 is appropriate.
int temp2 = 0; 

for (int i = 0; i < toReturn.Count; i++) {
     if (i == toReturn.Count - 2) { // Next-to-last element
         temp1 = toReturn[i];
     } else if (i == toReturn.Count - 1) { // Last element
         temp2 = toReturn[i];
     }
}

编译器要求 temp1temp2明确指定 在尝试读取它们的值之前。编译器不知道您的 for 循环将分配变量。它根本不知道 for 循环是否运行过。它也不知道你的 if 条件是否会是 true.

上面的代码确保 temp1temp2 已被分配给某事。如果您想确定是否 temp1temp2 已被分配 在循环, ,考虑跟踪这一点:

int temp1 = 0;
int temp2 = 0;
bool temp1Assigned = false;
bool temp2Assigned = false;

for (int i = 0; i < toReturn.Count; i++) {
     if (i == toReturn.Count - 2) { // Next-to-last element
         temp1 = toReturn[i];
         temp1Assigned = true;
     } else if (i == toReturn.Count - 1) { // Last element
         temp2 = toReturn[i];
         temp2Assigned = true;
     }
}

如果你想要一个默认值:

int count = toReturn.Count;
int temp1 = count > 1 ? toReturn[count - 2] : 0;
int temp2 = count  > 0 ? toReturn[count - 1] : 0;

如果您不关心默认值并且之前已检查计数:

int count = toReturn.Count;
int temp1 = toReturn[count - 2];
int temp2 = toReturn[count - 1];
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top