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

C#控制台:如何避免多if语句输入阻塞,且输入b时跳过首个判断?

解决C#控制台多次阻塞输入的问题

核心问题

你现在的代码每个if都调用Console.ReadLine(),等于每次要输入三次才能走完逻辑,自然没法输入"b"直接触发第二个分支——因为第一个if已经卡在那等你输入数字了。

最简单的修复方案:只读取一次输入

把输入先存到变量里,所有判断都用这个变量,避免重复阻塞:

// 只读取一次输入,存在变量里
string input = Console.ReadLine();

// 先判断是否是符合要求的数字
if (int.TryParse(input, out int userInput) && userInput >= 0 && userInput <= 50)
{
    DeleteDirectory(delDir, true);
    CloneDirectory(saves[userInput], cloneDir);
}
// 再判断是否是"b"
else if (input == "b")
{
    DeleteDirectory(saves[0], true);
    CloneDirectory(delDir, saves[0]);
}
// 再判断是否是"r"
else if (input == "r")
{
    DeleteDirectory(delDir, true);
    CloneDirectory(saves[0], cloneDir);
}
// 可选:输入不符合时提示
else
{
    Console.WriteLine("输入无效,请输入0-50的数字、b或r");
}

用switch case实现的版本

如果想用switch,先处理数字的情况,再处理字符串分支:

string input = Console.ReadLine();

// 尝试转数字,成功就走数字分支,失败走字符串判断
if (int.TryParse(input, out int userInput) && userInput >= 0 && userInput <= 50)
{
    DeleteDirectory(delDir, true);
    CloneDirectory(saves[userInput], cloneDir);
}
else
{
    switch (input)
    {
        case "b":
            DeleteDirectory(saves[0], true);
            CloneDirectory(delDir, saves[0]);
            break;
        case "r":
            DeleteDirectory(delDir, true);
            CloneDirectory(saves[0], cloneDir);
            break;
        default:
            Console.WriteLine("输入无效,请输入0-50的数字、b或r");
            break;
    }
}

关于非阻塞输入的补充

如果确实需要非阻塞(比如程序要同时做其他事,不用等输入),可以用Console.KeyAvailable检查有没有按键,再用Console.ReadKey(true)读取:

// 循环里检查是否有输入,不阻塞程序
while (true)
{
    if (Console.KeyAvailable)
    {
        ConsoleKeyInfo keyInfo = Console.ReadKey(true);
        string input = keyInfo.KeyChar.ToString();
        
        // 这里用input做判断逻辑,和上面一样
        if (int.TryParse(input, out int userInput) && userInput >=0 && userInput <=50)
        {
            // 数字逻辑
        }
        else if (input == "b")
        {
            // b的逻辑
        }
        // ...其他分支
    }

    // 这里放程序其他要执行的代码,不会被输入阻塞
    // Thread.Sleep(100); // 可选,减少CPU占用
}

但你的场景是命令行交互,一次输入对应一个操作,优先用单次读取输入的方案,非阻塞适合后台运行同时监听输入的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:10:39