变量inputBool是在when循环之外声明的,然后当我尝试将userInput解析为布尔值时,在when循环中设置变量。但是,一旦while循环退出,inputBool就会再次未声明!
但是,如果我用一个值(EG )初始化inputBool变量,那么它将在while循环中进行设置,然后将其设置为TryParse内部分配给它的任何内容,即使在with循环退出之后也是如此。
这是我想要的行为,但是当我不立即初始化变量时,它为什么不能工作呢?
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++;
}
发布于 2020-09-24 13:26:20
从流分析的角度来看,不能保证至少执行一次while
循环。当然,您不知道这是因为您的条件涉及一个初始化为bool
值的false
变量,但是编译器没有足够聪明地实现它。
因此,如果它至少不执行一次,那么inputBool
在结束时仍然是统一的,因此出现了错误。
您需要确保变量在所有代码路径中都已初始化。有两个可能的解决办法:
while
更改为do...while
。保证该变量至少执行一次,这将确保变量成为initialized.https://stackoverflow.com/questions/64054477
复制