gpt4 book ai didi

c# - 如何将可选参数传递给 winform 命令行

转载 作者:太空宇宙 更新时间:2023-11-03 23:34:16 25 4
gpt4 key购买 nike

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

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

简单来说,我希望用户能够通过年龄或姓名或两者来调用此函数命令行。例子...

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

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

最佳答案

据我了解和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 类中,您将在主函数内创建一个 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 ...
}

希望这对您有所帮助。

关于c# - 如何将可选参数传递给 winform 命令行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31088246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com