简体   繁体   English

将“--help”参数添加到C#控制台应用程序

[英]Adding “--help” parameter to C# console application

Almost all the .exe's I use via command line have a help function that gets called by the "--help" command. 我通过命令行使用的几乎所有.exe都有一个帮助函数,可以通过“--help”命令调用。

How do I implement this in C#? 我如何在C#中实现这一点? Is it as simple as checking whether or not the parameter in args[] is the string "--help"?? 是否像检查args []中的参数是否为字符串“--help”一样简单?

With *nix commands, it's common to obtain help either via -h or --help . 使用* nix命令,通常可以通过-h--help获得帮助。 Many windows commands will offer help with /? 许多Windows命令将提供/? . So it's not bad practice to do something like: 所以做一些像这样的事情是不错的做法:

public static void Main(string[] args)
{
    if (args.Length == 1 && HelpRequired(args[0]))
    {
        DisplayHelp();
    }
    else
    {
        ...
    }
}

private static bool HelpRequired(string param)
{
    return param == "-h" || param == "--help" || param == "/?";
}

AC# snippet for processing the command line across multiple cultures is... 用于处理跨多种文化的命令行的AC#片段是......

        string[] args = Environment.GetCommandLineArgs();
        if (args.Length == 2)
        {
            if (args[1].ToLower(CultureInfo.InvariantCulture).IndexOf("help", System.StringComparison.Ordinal) >= 0)
            {
                // give help
            }
        }

The detection logic can be combined with "?" 检测逻辑可以与“?”组合 or "/?" 要么 ”/?” or any other combination that covers all expected cases. 或涵盖所有预期案件的任何其他组合。

NOTE: when you get the arguments from the Environment, arg[0] is populated by the loader. 注意:从环境中获取参数时,加载器会填充arg [0]。 The first 'user' argument is in arg[1]. 第一个'用户'参数在arg [1]中。

Is it as simple as checking whether or not the parameter in args[] is the string "--help"?? 是否像检查args []中的参数是否为字符串“--help”一样简单?

Yes. 是。

This is why different console programs sometimes have a different convention for how to get at the help information. 这就是为什么不同的控制台程序有时会对如何获取帮助信息有不同的约定。

Yes. 是。 AFAIK, same as compring the arguments and displaying some strings on the screen. AFAIK,与编写参数并在屏幕上显示一些字符串相同。

static void Main( string[] args )
{
    if(  args != null && args.Length == 1 )
    {
        if( args[0].ToLower() == "help" )
        {
             ShowHelpHere();
        }
    }

}

I use an intersection over a small collection of help commands. 我在一小组帮助命令上使用交集。 If I constrain myself tightly to your question; 如果我严格限制自己的问题; it winds up looking like this: 它看起来像这样:

static bool ShowHelpRequired(IEnumerable<string> args)
{
    return args.Select(s => s.ToLowerInvariant())
        .Intersect(new[] { "help", "/?", "--help", "-help", "-h" }).Any();
}

Broadening the scope (just a little); 扩大范围(只是一点点); I wind up with a method called ParseArgs that returns a boolean that is true if either parsing failed or help is required . 我风与一种称为ParseArgs返回一个boolean是true,如果无论是 分析失败需要帮助 This method also has an out parameter that stores parsed program parameters. 此方法还有一个out参数,用于存储已解析的程序参数。

    /// <summary>
    /// Parses the arguments; sets the params struct.
    /// </summary>
    /// <param name="argv">The argv.</param>
    /// <param name="paramStruct">The parameter structure.</param>
    /// <returns>true if <see cref="ShowHelp"/> needed.</returns>
    static bool ParseArgs(IEnumerable<string> argv, out ParamStruct paramStruct)
    {
        paramStruct = new ParamStruct();

        try { /* TODO: parse the arguments and set struct fields */ }
        catch { return false; }

        return argv.Select(s => s.ToLowerInvariant()).Intersect(new[] { "help", "/?", "--help", "-help", "-h" }).Any();
    }

This makes things very convenient in the main and allows for good separation between ShowHelp and ParseArgs . 这使得主要内容非常方便,并允许ShowHelpParseArgs之间的良好分离。

    if (!ParseArgs(argv, out parameters))
    {
        ShowHelp();

        return;
    }

Notes 笔记

  • Instead of having ParseArgs in Main one variation is to place the ParseArgs method into parameters struct as a static method. 而不是在Main中使用ParseArgs ,而是将ParseArgs方法作为静态方法放入参数struct中。
  • The catch should only catch parsing exceptions; catch应该捕获解析异常; code does not reflect this. 代码不反映这一点。

You can use the CommandLineParser nugget package. 您可以使用CommandLineParser块包。 Then you can create an Options class, all metadata to provide help and validation. 然后,您可以创建一个Options类,所有元数据都可以提供帮助和验证。 Pretty amazing and simple to implement. 实现相当惊人和简单。

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

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