You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Authentication方法时内部while循环未进入执行的问题咨询

问题核心原因

你代码里的while循环判断条件存在两个叠加的错误:

  • 混淆了赋值运算符=和相等比较运算符==:你要判断isAuthenticated是否为false时,应该用双等号==做比较,而不是单等号赋值。
  • 运算符优先级问题:C#中&&逻辑与运算符的优先级高于=赋值运算符,你写的while (isAuthenticated = false && count > 0)实际执行逻辑等同于isAuthenticated = (false && count > 0),false && 任意表达式结果恒为false,直接导致循环条件永远不成立,自然不会执行循环体。

修复方案

将while循环的条件修改为以下任意一种正确写法即可:

  1. 简洁写法(推荐):
while (!isAuthenticated && count > 0)
  1. 显式比较写法:
while (isAuthenticated == false && count > 0)

修复后完整代码

public static bool Authentication()
{
    bool isAuthenticated = false;
    int count = 4;
    // 修复后的判断条件
    while (!isAuthenticated && count > 0)
    {
        Console.WriteLine("Please insert your 4 digit PIN");
        string pin = Console.ReadLine();
        if (pin == "1704")
        {
            isAuthenticated = true;
            return isAuthenticated;
        }
        else
        {
            count--;
            Console.WriteLine($"Wrong PIN: {count} Input remained ");
        }

    }

    return isAuthenticated;
}

内容的提问来源于stack exchange,提问作者Marco Stevanella

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 01:54:05