【问题标题】:How to pass optional arguments to winform commandline如何将可选参数传递给 winform 命令行
【发布时间】:2015-09-14 07:07:42
【问题描述】:

所以我过去编写过一些工具,我将命令行参数传递给 winforms c# 工具。如何传递可选的特定参数。

 Static void test(string name="bill", int age=5, string location = "home")
 {
      Console.writeline (name)
      Console.writeline (age)
 }

简单来说,我希望用户能够在命令行中调用此函数,传递年龄或姓名或两者兼而有之。 例子...

测试名称:“JOEY” 测试地点:“床”年龄:5

也许对于我编写命令行参数的方式有一个建议,我以可以传递可选参数的方式解析它。欢迎提出建议。

【问题讨论】:

  • 您的问题含糊不清。您想从命令行接收这些参数吗?还是希望其他用户调用此方法?
  • 为什么不为方法添加重载?
  • 我会查找重载。我从未听说过或使用过它们。
  • 是的,我想使用命令行传递它们来运行函数。

标签: c# command-line-arguments


【解决方案1】:

据我了解和 devdigital 所建议的,您可以使用 Command Line Parser Library(可使用 NuGet)。 我在我的项目中使用它以便在不同的状态下启动应用程序。 首先,您将定义所有接受的参数(可以将其中一些设置为可选参数,有关库文档的更多信息)

public class CommandLineArgs
{
    [Option('t', "type", Required = false, HelpText = "Type of the application [safedispatch, safenet]")]
    public string AppType { get; set; }

    [Option('c', null, HelpText = "Enable the console for this application")]
    public bool Console { get; set; }

    [Option('l', null, HelpText = "Enable the logs for this application")]
    public bool Log { get; set; }

    [Option('h', null, HelpText = "Help for this command line")]
    public bool Help { get; set; }

    [HelpOption]
    public string GetUsage()
    {
        // this without using CommandLine.Text
        //  or using HelpText.AutoBuild
        var usage = HelpText.AutoBuild(this);

        return usage.ToString();
    }
}

接下来,在 Program.cs 类上,在 main 函数中,您将创建一个 CommandLineArgs 对象并解析接收到的参数。最后,您将根据传递给您的参数做出决定。

static void Main(string[] args)
{
var cmdArgs = new CommandLineArgs();
if (args.Length > 0 && CommandLine.Parser.Default.ParseArguments(args, cmdArgs))
    {
    // display the help
    if (cmdArgs.Help)
    {
          Utils.WriteLine(cmdArgs.GetUsage());
          Console.ReadKey();
    }

    // display the console
    if (!cmdArgs.Console)
    {
          // hide the console window                   
          setConsoleWindowVisibility(false, Console.Title);
    }

   // verify other console parameters and run your test function
}
else if (args.Length == 0)
{
     // no command line args specified
}

// other lines ...
}

希望这会有所帮助。

【讨论】:

  • 感谢您的帮助。这有助于让我有足够的进展来让某些事情发挥作用并进行更多研究
【解决方案2】:

一个建议是使用命令行解析库,例如 Command Line Parser LibraryFluent Command Line Parser,两者都可以通过 NuGet 获得。

【讨论】:

    猜你喜欢
    • 2013-10-11
    • 1970-01-01
    • 2012-09-01
    • 2020-08-02
    • 2014-01-13
    • 2020-09-02
    • 2014-05-03
    • 2011-10-14
    相关资源
    最近更新 更多