变量inputBool在while循环外声明,然后在尝试将userInput解析为布尔值时在while循环内设置。但是,一旦退出while循环,inputBool便会再次变为未声明!
但是,如果我使用值(EG false)初始化inputBool变量,它将在while循环内进行设置,然后即使在退出while循环后,也将保持设置为TryParse内部分配的任何值。
这是我想要的行为,但是当我不立即初始化变量时为什么不起作用?
foreach (string question in questions)
{
bool isBool = false;
// inputBool declared here.
bool inputBool;
string userInput;
while (!isBool)
{
Console.WriteLine(question);
userInput = Console.ReadLine();
// inputBool gets assigned a value here in the TryParse.
isBool = Boolean.TryParse(userInput, out inputBool);
if (!isBool) Console.WriteLine("Please respond with 'true' or 'false'.");
}
// inputBool is unassigned here!
answers[askingIndex] = inputBool;
askingIndex++;
}
从流分析的角度来看,不能保证while
循环至少执行一次。当然,您会另外知道,因为您的条件涉及一个bool
初始化为的值的变量false
,但是编译器不够聪明,无法实现它。
因此,如果它至少执行一次,inputBool
则最后仍将被统一化,从而产生错误。
您需要确保在所有代码路径中初始化变量。有两个可能的修复:
while
改为do...while
。确保至少执行一次,以确保变量被初始化。本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句