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

C#控制台简易登录程序问题:输入与对象列表比对失败求助

问题核心原因

你Login方法里的判断逻辑完全搞错了——userName == Loginuser && passWord == Loginuser这行代码是拿输入的字符串(用户名、密码)直接和整个List<Loginuser>集合做比较,类型都不匹配,肯定永远返回false,自然不管输入对错都进不去主菜单。

修正方案

正确的做法是遍历集合里的每个用户对象,检查是否存在userid和输入用户名匹配、同时userpass和输入密码匹配的对象。可以用LINQ简化判断,也可以用foreach循环遍历。

修正后的Login方法(LINQ版本)

void Login()
{
    Console.WriteLine("Welcome");
    Console.Write("Enter Username: ");
    string userName = Console.ReadLine();
    Console.Write("Enter Password: ");
    string passWord = Console.ReadLine();

    // 查询集合中是否存在匹配的用户
    bool isLoginValid = Loginuser.Any(u => u.userid == userName && u.userpass == passWord);

    if (isLoginValid)
    {
        Console.WriteLine("Welcome " + userName);
        Console.ReadLine();
        MainMenu(); // 假设你已实现MainMenu方法
    }
    else
    {
        Console.WriteLine("用户名或密码错误,按回车重试");
        Console.ReadLine();
        Login();
    }
}

修正后的Login方法(foreach循环版本)

void Login()
{
    Console.WriteLine("Welcome");
    Console.Write("Enter Username: ");
    string userName = Console.ReadLine();
    Console.Write("Enter Password: ");
    string passWord = Console.ReadLine();

    bool isLoginValid = false;
    // 遍历集合逐个检查用户信息
    foreach (var user in Loginuser)
    {
        if (user.userid == userName && user.userpass == passWord)
        {
            isLoginValid = true;
            break;
        }
    }

    if (isLoginValid)
    {
        Console.WriteLine("Welcome " + userName);
        Console.ReadLine();
        MainMenu();
    }
    else
    {
        Console.WriteLine("用户名或密码错误,按回车重试");
        Console.ReadLine();
        Login();
    }
}
额外小提醒
  1. 变量命名要规范,集合名Loginuser建议改成loginUsers(小写开头+复数),避免和类名Loginuser混淆,减少代码歧义。
  2. Convert.ToInt32(Console.ReadLine())如果用户输入非数字会直接崩溃,可以改用int.TryParse做容错处理,比如:
int val;
if (!int.TryParse(Console.ReadLine(), out val))
{
    Console.WriteLine("请输入有效数字");
    Console.ReadLine();
    Loginscreen();
    return;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 16:50:37