重要
System.CommandLine
目前为预览版,本文档适用于版本 2.0 beta 5。
某些信息与预发布产品有关,该产品在发布前可能会进行大幅修改。 Microsoft对此处提供的信息不作任何明示或暗示的保证。
默认情况下, System.CommandLine 提供一组内置分析程序,可分析许多常见类型:
bool
-
byte
和sbyte
-
short
和ushort
-
int
和uint
-
long
和ulong
-
float
和double
decimal
-
DateTime
和DateTimeOffset
-
DateOnly
和TimeOnly
Guid
- FileSystemInfo、FileInfo 和 DirectoryInfo
- 枚举
- 列出的类型的数组和列表
不支持其他类型的类型,但你可以为其创建自定义分析程序。 还可以验证已分析的值,这在需要确保输入满足特定条件时非常有用。
验证程序
每个选项、参数和命令都可以有一个或多个验证程序。 验证程序用于确保分析的值满足特定条件。 例如,可以验证数字是否为正数,或者字符串不为空。 还可以创建针对多个条件进行检查的复杂验证程序。
中的每个 System.CommandLine 符号类型都有一个 Validators
包含验证程序列表的属性。 验证程序在分析输入后执行,如果验证失败,则可以报告错误。
若要提供自定义验证代码,请调用 System.CommandLine.Option.Validators.Add
选项或参数(或命令),如以下示例所示:
Option<int> delayOption = new("--delay");
delayOption.Validators.Add(result =>
{
if (result.GetValue(delayOption) < 1)
{
result.AddError("Must be greater than 0");
}
});
System.CommandLine 提供一组可用于验证常见类型的内置验证程序:
-
AcceptExistingOnly
- 将给定的选项或参数配置为仅接受对应于现有文件或目录的值。 -
AcceptLegalFileNamesOnly
- 将给定的选项或参数配置为仅接受表示合法文件名的值。 -
AcceptOnlyFromAmong
- 将给定的选项或参数配置为仅接受一组指定值中的值。
自定义分析程序
自定义分析程序需要分析没有默认分析程序(例如复杂类型)的类型。 它们还可用于以与内置分析程序不同的方式分析受支持的类型。
假设你有一个 Person
类型:
public class Person
{
public string? FirstName { get; set; }
public string? LastName { get; set; }
}
可以读取值并在命令作中创建实例 Person
:
rootCommand.SetAction(parseResult =>
{
Person person = new()
{
FirstName = parseResult.GetValue(firstNameOption),
LastName = parseResult.GetValue(lastNameOption)
};
DoRootCommand(parseResult.GetValue(fileOption), person);
});
使用自定义分析器,可以采用与获取基元值相同的方式获取自定义类型:
Option<Person?> personOption = new("--person")
{
Description = "An option whose argument is parsed as a Person",
CustomParser = result =>
{
if (result.Tokens.Count != 2)
{
result.AddError("--person requires two arguments");
return null;
}
return new Person
{
FirstName = result.Tokens.First().Value,
LastName = result.Tokens.Last().Value
};
}
};
如果要分析并验证输入,请使用 CustomParser
委托,如以下示例所示:
Option<int> delayOption = new("--delay")
{
Description = "An option whose argument is parsed as an int.",
CustomParser = result =>
{
if (!result.Tokens.Any())
{
return 42;
}
if (int.TryParse(result.Tokens.Single().Value, out var delay))
{
if (delay < 1)
{
result.AddError("Must be greater than 0");
}
return delay;
}
else
{
result.AddError("Not an int.");
return 0; // Ignored.
}
}
};
下面是一些可以使用验证程序无法执行的作 CustomParser
的示例:
- 分析其他类型的输入字符串(例如,分析“1,2,3”)。
int[]
- 动态 arity。 例如,如果两个参数定义为字符串数组,并且必须在命令行输入中处理字符串序列,则
System.CommandLine.Parsing.ArgumentResult.OnlyTake
该方法使你可以动态划分参数之间的输入字符串。