如何配置分析器 System.CommandLine

重要

System.CommandLine 目前为预览版,本文档适用于版本 2.0 beta 5。 某些信息与预发布产品有关,该产品在发布前可能会进行大幅修改。 Microsoft对此处提供的信息不作任何明示或暗示的保证。

System.CommandLine.CommandLineConfiguration 是一个类,提供用于配置分析程序的属性。 它是每个 Parse 方法的可选参数,例如 System.CommandLine.Command.ParseSystem.CommandLine.Parsing.CommandLineParser.Parse。 如果未提供,则使用默认配置。

每个 System.CommandLine.ParseResult 实例都有一个 System.CommandLine.ParseResult.Configuration 返回用于分析的配置的属性。

标准输出和错误

System.CommandLine.CommandLineConfiguration 使测试以及许多扩展性方案比使用 System.Console更容易。 它公开两个 TextWriter 属性: OutputError。 这些实例可以设置为任何 TextWriter 实例,例如 StringWriter可用于捕获用于测试的输出。

让我们定义写入标准输出的简单命令:

Option<FileInfo?> fileOption = new("--file")
{
    Description = "An option whose argument is parsed as a FileInfo"
};

RootCommand rootCommand = new("Configuration sample")
{
    fileOption
};

rootCommand.SetAction((parseResult) =>
{
    FileInfo? fileOptionValue = parseResult.GetValue(fileOption);
    parseResult.Configuration.Output.WriteLine($"File option value: {fileOptionValue?.FullName}");
});

现在,让我们来 CommandLineConfiguration 捕获输出:

StringWriter output = new();
CommandLineConfiguration configuration = new(rootCommand)
{
    Output = output,
    Error = TextWriter.Null
};

configuration.Parse("-h").Invoke();
Debug.Assert(output.ToString().Contains("Configuration sample"));

EnablePosixBundling

默认情况下启用单字符选项捆绑,但可以通过将System.CommandLine.CommandLineConfiguration.EnablePosixBundling属性设置为 来false禁用它。

ProcessTerminationTimeout

可以通过属性配置System.CommandLine.CommandLineConfiguration.ProcessTerminationTimeout进程终止超时。 默认值为 2 秒。

ResponseFileTokenReplacer

默认情况下启用响应文件 ,但可以通过将 System.CommandLine.CommandLineConfiguration.ResponseFileTokenReplacer 属性设置为 来 null禁用它们。 还可以提供自定义实现来自定义响应文件的处理方式。

EnableDefaultExceptionHandler

默认情况下,在调用命令期间引发的所有未经处理的异常都会被捕获并报告给用户。 通过将属性设置为 System.CommandLine.CommandLineConfiguration.EnableDefaultExceptionHandlerfalse.,可以禁用此行为。 如果要以自定义方式处理异常,例如记录异常或提供不同的用户体验,这非常有用。

派生类

System.CommandLine.CommandLineConfiguration 未密封,因此可以派生自它以添加自定义属性或方法。 如果要提供特定于应用程序的其他配置选项,这非常有用。

另请参阅