英文:
How to get command line parameters in specific format?
问题
例如,我们有选项 "--date"。
我使用 System.CommandLine
库从命令行获取选项,它可以与以下格式一起使用:"--date 2023-02-06",但我想让它支持类似以下格式的工作:"--date=2023-02-06"。有办法吗?
英文:
For example, we have option "--date".
I use System.CommandLine
library to get options from command line and it works with such format:
"--date 2023-02-06", but I want it to work with format kind of: "--date=2023-02-06". Is there a way to do this?
答案1
得分: 1
如果您不介意使用一个测试版的 Microsoft 库,您可以使用 System.CommandLine。
根据选项参数分隔符:
选项参数分隔符
System.CommandLine 允许您使用空格、'=' 或 ':' 作为选项名称和其参数之间的分隔符。例如,以下命令是等效的:
dotnet build -v quiet dotnet build -v=quiet dotnet build -v:quiet
例如(这是修改过的教程:开始使用 System.CommandLine):
// dotnet add package System.CommandLine --prerelease
using System.CommandLine;
internal class Program
{
static async Task<int> Main(string[] args)
{
var date = new Option<string?>(
name: "--date",
description: "TODO");
var rootCommand = new RootCommand("TODO");
rootCommand.AddOption(date);
rootCommand.SetHandler((date) =>
{
Run(date!);
},
date);
return await rootCommand.InvokeAsync(args);
}
static void Run(string date)
{
Console.WriteLine(date);
}
}
然后我们可以执行以下命令:
PS C:\git\games\bin\Release\net6.0\win10-x64\publish> .\games.exe --date 2023-02-06
2023-02-06
PS C:\git\games\bin\Release\net6.0\win10-x64\publish> .\games.exe --date:2023-02-06
2023-02-06
PS C:\git\games\bin\Release\net6.0\win10-x64\publish> .\games.exe --date=2023-02-06
2023-02-06
英文:
If you don't mind using a beta Microsoft library you could use System.CommandLine.
From Option-argument delimiters:
> Option-argument delimiters
>
> System.CommandLine lets you use a space, '=', or ':' as the delimiter between an option name and its argument. For example, the following commands are equivalent:
>
>
> dotnet build -v quiet
> dotnet build -v=quiet
> dotnet build -v:quiet
>
For example (This is modified Tutorial: Get started with System.CommandLine):
// dotnet add package System.CommandLine --prerelease
using System.CommandLine;
internal class Program
{
static async Task<int> Main(string[] args)
{
var date = new Option<string?>(
name: "--date",
description: "TODO");
var rootCommand = new RootCommand("TODO");
rootCommand.AddOption(date);
rootCommand.SetHandler((date) =>
{
Run(date!);
},
date);
return await rootCommand.InvokeAsync(args);
}
static void Run(string date)
{
Console.WriteLine(date);
}
}
Then we can:
PS C:\git\games\bin\Release\net6.0\win10-x64\publish> .\games.exe --date 2023-02-06
2023-02-06
PS C:\git\games\bin\Release\net6.0\win10-x64\publish> .\games.exe --date:2023-02-06
2023-02-06
PS C:\git\games\bin\Release\net6.0\win10-x64\publish> .\games.exe --date=2023-02-06
2023-02-06
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论