命令行解析器解析值 eventhoug 未指定?
Command line Parser parses value eventhoug its not specified?
我已经开始使用这个https://github.com/commandlineparser/commandline
将解析的输入参数传递给我的应用程序。
我的问题是传递的输入参数不是必需的,这意味着您可以在不指定它们的情况下启动应用程序。
到目前为止,我已经这样定义了我的命令行选项
public class CommandLineOptions
{
[Option(longName: "client-id", Required = false, HelpText = "Id of the client")]
public string ClientId { get; set; }
[Option(longName: "pw", Required = false, HelpText = "pw.")]
public string Password{ get; set; }
}
我主要是这样解析它们的
Access access= Parser.Default.ParseArguments<CommandLineOptions>(args)
.MapResult(parsedFunc: (CommandLineOptions opts) => new Access(opts.ClientId, opts.Password),
notParsedFunc: (IEnumerable<Error> a) => new Access());
我想在指定的情况下使用 parsedfunc:
,在未指定的情况下使用 notParsedFunc:
。
但这总是会触发 parsedFunc
,并且由于两个参数的值都是 null
,我的内部方法失败了吗?
我也试过将选项更改为不需要,然后在控制台中抛出一个错误 window 没有指定这些参数,但触发了正确的方法。
来自documentation :
If parsing succeeds, you'll get a derived Parsed type that exposes an instance of T through its Value property.
If parsing fails, you'll get a derived NotParsed type with errors present in Errors sequence.
NotParsed
解析失败时调用,但在你的情况下解析成功,因为允许空密码。
您需要使用 Parsed
并手动检查参数是否存在:
Access access = Parser.Default.ParseArguments<CommandLineOptions>(args)
.MapResult(
opts => opts.Password == null ? new Access() : new Access(opts.ClientId, opts.Password),
_ => null
);
if(access == null)
{
// Fail to create access
// Close withe exit code 1
Environment.Exit(1);
}
我已经开始使用这个https://github.com/commandlineparser/commandline 将解析的输入参数传递给我的应用程序。
我的问题是传递的输入参数不是必需的,这意味着您可以在不指定它们的情况下启动应用程序。
到目前为止,我已经这样定义了我的命令行选项
public class CommandLineOptions
{
[Option(longName: "client-id", Required = false, HelpText = "Id of the client")]
public string ClientId { get; set; }
[Option(longName: "pw", Required = false, HelpText = "pw.")]
public string Password{ get; set; }
}
我主要是这样解析它们的
Access access= Parser.Default.ParseArguments<CommandLineOptions>(args)
.MapResult(parsedFunc: (CommandLineOptions opts) => new Access(opts.ClientId, opts.Password),
notParsedFunc: (IEnumerable<Error> a) => new Access());
我想在指定的情况下使用 parsedfunc:
,在未指定的情况下使用 notParsedFunc:
。
但这总是会触发 parsedFunc
,并且由于两个参数的值都是 null
,我的内部方法失败了吗?
我也试过将选项更改为不需要,然后在控制台中抛出一个错误 window 没有指定这些参数,但触发了正确的方法。
来自documentation :
If parsing succeeds, you'll get a derived Parsed type that exposes an instance of T through its Value property.
If parsing fails, you'll get a derived NotParsed type with errors present in Errors sequence.
NotParsed
解析失败时调用,但在你的情况下解析成功,因为允许空密码。
您需要使用 Parsed
并手动检查参数是否存在:
Access access = Parser.Default.ParseArguments<CommandLineOptions>(args)
.MapResult(
opts => opts.Password == null ? new Access() : new Access(opts.ClientId, opts.Password),
_ => null
);
if(access == null)
{
// Fail to create access
// Close withe exit code 1
Environment.Exit(1);
}