简体   繁体   English

如何通过/检查指定的 arguments?

[英]How to pass/check for specified arguments?

I'm currently writing a C# console application and would like to give the user the ability to chose what feature to be executed.我目前正在编写一个 C# 控制台应用程序,并希望让用户能够选择要执行的功能。 For example, when I start MyApp.exe -help the help should show, or when I start MyApp.exe -shutdown the computer should shutdown.例如,当我启动MyApp.exe -help时应该显示帮助,或者当我启动MyApp.exe -shutdown时计算机应该关闭。 How do I pass/check that?我如何通过/检查?

My current code doesn't seem to work:我当前的代码似乎不起作用:

static void Main(string[] args)
{
        if (args.Equals("-help"))
        {
            Console.WriteLine("Some help here...");
        }
}
    static void Main(string[] args)
    {
        ProcesArguments(args);
    }

    static void ProcesArguments(string[] parameters)
    {
        foreach (var parameter in parameters)
        {
            switch (parameter.ToLower())
            {
                case "-help":
                    DisplayHelp();
                    break;
                case "-reboot":
                    RebootComputer();
                    break;
            }
        }
    }

    static void DisplayHelp()
    {
        Console.WriteLine($"Syntax: {System.AppDomain.CurrentDomain.FriendlyName} <Parameter>");
        // ...
    }

    static void RebootComputer()
    {
        // ...
    }

Args is an array, so you have to reference the argument by its index. Args 是一个数组,因此您必须通过其索引引用该参数。 So args[0] corresponds to the first argument passed in. In addition, check the array length first to ensure an argument was even provided before you try to access it.因此args[0]对应于传入的第一个参数。此外,请先检查数组长度以确保在尝试访问之前甚至提供了参数。

static void Main(string[] args)
{
    if (args.Length > 0 && args[0] == "-help")
    {
        Console.WriteLine("Some help here...");
    }
}

args is an array so you need to look for -help occurrence in it. args是一个数组,因此您需要在其中查找-help的出现。 You can achieve it using String.Contains() method.您可以使用String.Contains()方法来实现它。

static void Main(string[] args)
{
    if (args.Contains("-help"))
    {
        Console.WriteLine("Some help here...");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM