当Console.ReadLine()执行时,C#控制台应用程序执行代码

时间:2017-07-27 15:03:44

标签: c# events console-application

我目前正在使用控制台应用程序,我有一些逻辑可以获得3个不同的用户输入。我设计了应用程序,以便用户可以输入Q' Q'或者' q'随时退出该计划。但是,我目前正在完成此操作的方式是通过每个用户输入后的if语句(使用Console.ReadLine()。)

我认为最好的解决方案是在一个地方有一段代码退出程序,并在执行ReadLine()时自动调用,并检查输入是否为' q'或者' Q'。我很好奇是否有办法做这样的事情???

这是我现在的代码

Console.WriteLine("Please give me a source and destination directory...(Enter 'Q' anytime to exit)");

        Console.Write("Enter source path: ");
        _sourcePath = Console.ReadLine();
        if (_sourcePath.Equals("q", StringComparison.CurrentCultureIgnoreCase))
        {
            Environment.Exit(Environment.ExitCode);
        }

        Console.Write("Enter destination path: ");
        _destinationPath = Console.ReadLine();
        if (_destinationPath.Equals("q", StringComparison.CurrentCultureIgnoreCase))
        {
            Environment.Exit(Environment.ExitCode);
        }

        Console.Write("Do you want detailed information displayed during the copy process? ");
        string response = Console.ReadLine();
        if (response.Equals("q", StringComparison.CurrentCultureIgnoreCase))
        {
            Environment.Exit(Environment.ExitCode);
        }

        if (response?.Substring(0, 1).ToUpper() == "Y")
        {
            _detailedReport = true;
        }

最好删除if块,并在执行时检查来自Console.ReadLine()的传入值...

2 个答案:

答案 0 :(得分:1)

您可以创建一个函数来获取用户的输入,在Console.ReadLine()之后,只需对输入执行任何处理(退出'q'),然后再返回它。

static void Main(string[] args)
{
    Console.Write("Enter source path: ");
    var _sourcePath = GetInput();

    Console.Write("Enter destination path: ");
    var _destinationPath = GetInput();

    Console.Write("Do you want detailed information displayed during the copy process? ");
    var response = GetInput();

    var _detailedReport = response?.Substring(0, 1)
        .Equals("y", StringComparison.CurrentCultureIgnoreCase);
}

private static string GetInput()
{
    var input = Console.ReadLine();
    if (input.Equals("q", StringComparison.CurrentCultureIgnoreCase))
        Environment.Exit(Environment.ExitCode);
    return input;
}

答案 1 :(得分:1)

我担心没有直接的方式来挂钩ReadLine()调用。用你自己的方法“ReadLine”包装它可能会起作用,比如像

static string ReadLine()
{
    string line = Console.ReadLine();

    if (line.Equals("q", StringComparison.CurrentCultureIgnoreCase))
    {
        Environment.Exit(Environment.ExitCode);
    }
    //Other global stuff

    return line;
}

//Elsewhere
Console.Write("Enter source path: ");
_sourcePath = ReadLine(); //Note: No 'Console.' beforehand. This is your method!
Console.Write("Enter destination path: ");
_destinationPath = ReadLine();
Console.Write("Do you want detailed information displayed during the copy process? ");
string response = ReadLine();

if (response?.Substring(0, 1).ToUpper() == "Y")
{
    _detailedReport = true;
}