重要
System.CommandLine
目前为预览版。 本文档适用于版本 2.0 beta 5。
某些信息与预发布产品有关,该产品可能在发布前进行大幅修改。 Microsoft对此处提供的信息不作任何明示或暗示的保证。
CommandLineConfiguration 是一个类,提供用于配置分析程序的属性。 它是每个 Parse
方法的可选参数,例如 Command.Parse 和 CommandLineParser.Parse。 如果未提供,则使用默认配置。
ParseResult 具有返回 Configuration 用于分析的配置的属性。
标准输出和错误
CommandLineConfiguration
使测试以及许多扩展性方案比使用 System.Console
更容易。 它公开两个 TextWriter
属性: Output
和 Error
。 这些实例可以设置为任何 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
禁用它们。 还可以提供自定义实现来定制响应文件的处理方式。
启用默认异常处理程序
默认情况下,在调用命令期间引发的所有未经处理的异常都会被捕获并报告给用户。 通过将属性设置为 System.CommandLine.CommandLineConfiguration.EnableDefaultExceptionHandler
false
.,可以禁用此行为。 如果要以自定义方式处理异常,例如记录异常或提供不同的用户体验,这非常有用。
派生类
System.CommandLine.CommandLineConfiguration
未密封,因此可以派生自它以添加自定义属性或方法。 如果要提供特定于应用程序的其他配置选项,这非常有用。