0

我有几个变量需要在 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'”错误。这段代码甚至没有运行,它只是坐在一个永远不会被调用的方法中。如果这有帮助,我正在尝试在另一个循环中使用变量。

4

6 回答 6

11

为什么不干...

int temp1 = 0;
int temp2 = 0;
    if (toReturn.Count > 1)
        temp1 = toReturn[toReturn.Count - 2];
    if (toReturn.Count > 0)
        temp2 = toReturn[toReturn.Count - 1];
于 2009-09-29T20:55:01.953 回答
5

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

于 2009-09-29T20:53:33.157 回答
1

这是做什么的?

if (toReturn.Count > 1) {
    temp1 = toReturn[toReturn.Count - 2]
    temp2 = toReturn[toReturn.Count - 1]
}
于 2009-09-29T20:55:51.700 回答
0

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

于 2009-09-29T20:57:50.027 回答
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];
     }
}

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

上面的代码确保temp1temp2已分配给某些东西。如果您想确定是否temp1并且temp2在循环中分配,请考虑跟踪以下内容:

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;
     }
}
于 2009-09-29T21:05:38.810 回答
0

如果你想要一个默认值:

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];
于 2009-09-29T21:06:05.503 回答