【发布时间】:2025-12-07 09:55:01
【问题描述】:
我想使用 https://natemcmaster.github.io/CommandLineUtils/ 使用不支持开箱即用的选项类型和异步执行方法的属性。
class Program
{
//--from-date="2018-01-01" --to-date="2018-07-01"
[Option()]
public DateTime? FromDate { get; }
[Option()]
public DateTime? ToDate { get; }
private async Task OnExecuteAsync()
{
//do the actual work
}
}
如果我使用字符串类型,静态 ExecuteAsync 可以正常工作。
var ret = CommandLineApplication.ExecuteAsync<Program>(args);
但如果参数是 DateTime? 类型,我必须添加自定义解析器(如 Support passing Uri values #97 中的建议)
我已经创建了一个应用对象,添加了解析器,分配了 OnExecute 并调用了执行方法
private static int AddValueParsersAndExecute(string[] args)
{
var app = new CommandLineApplication<Program>();
app.ValueParsers.AddOrReplace(new NullableDateTimeParser());
app.OnExecute((Func<Task>) new Program().OnExecuteAsync);
var ret = app.Execute(args);
return ret;
}
不幸的是,当我通过 --from-date="2018-01-01" --to-date="2018-07-01"(并且我尝试了不同的选项名称变体)时,它会导致错误
McMaster.Extensions.CommandLineUtils.CommandParsingException
HResult=0x80131500
Message=Unrecognized option '--from-date=2018-01-01'
Source=McMaster.Extensions.CommandLineUtils
StackTrace:
at McMaster.Extensions.CommandLineUtils.CommandLineProcessor.HandleUnexpectedArg(String argTypeName) in C:\projects\commandlineutils\src\CommandLineUtils\Internal\CommandLineProcessor.cs:line 246
at McMaster.Extensions.CommandLineUtils.CommandLineProcessor.ProcessOption() in C:\projects\commandlineutils\src\CommandLineUtils\Internal\CommandLineProcessor.cs:line 162
at McMaster.Extensions.CommandLineUtils.CommandLineProcessor.ProcessNext() in C:\projects\commandlineutils\src\CommandLineUtils\Internal\CommandLineProcessor.cs:line 62
at McMaster.Extensions.CommandLineUtils.CommandLineProcessor.Process() in C:\projects\commandlineutils\src\CommandLineUtils\Internal\CommandLineProcessor.cs:line 35
at McMaster.Extensions.CommandLineUtils.CommandLineApplication.Parse(String[] args) in C:\projects\commandlineutils\src\CommandLineUtils\CommandLineApplication.cs:line 532
at McMaster.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args) in C:\projects\commandlineutils\src\CommandLineUtils\CommandLineApplication.cs:line 611
at BlobsProcessor.Program.AddValueParsersAndExecute(String[] args)
谁能建议,是否可以结合 ExecuteAsync、属性选项和自定义解析器?
到目前为止,我发现有字符串选项并将它们解析为 DateTime 的解决方法?在我的应用程序中。
【问题讨论】:
标签: .net-core commandlineutils