[英]Trouble with local variables in C#
我有几个变量需要在for循环内分配。 显然,当循环退出时,C#会忽略其中发生的任何事情,并且变量将返回其原始状态。 具体来说,我需要它们成为List的倒数第二个元素。 这是代码:
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];
}
}
编译器要求在尝试读取它们的值之前,必须先分配 temp1
和temp2
。 编译器不知道您的for循环会分配变量。 它不知道for循环是否曾经运行过。 它还不知道您的if条件是否为true
。
上面的代码确保已将temp1
和temp2
分配给某些对象。 如果要确定是否已在循环中分配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;
}
}
如果要使用默认值:
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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.