c#CommandLine.Parser - 使用接受Action <ParserSettings>的构造函数

Ste*_*ott 2 c# command-line command-line-parsing

我正在使用此代码,但我收到编译器警告,不推荐使用此创建方法.由于我想删除警告,并转移到较新版本,我想更正代码,但我无法使CommandLineParser 1.9.7库工作.

CommandLine.Parser OptionParser = new CommandLine.Parser(new CommandLine.ParserSettings
     {
        CaseSensitive = UseCaseSensitive,
        IgnoreUnknownArguments = IgnoreUnknownOptions,
        MutuallyExclusive = EnableMutuallyExclusive
     }
);
bool Result = OptionParser.ParseArguments(Args, this);
Run Code Online (Sandbox Code Playgroud)

根据命令行的参数和传递的选项,此代码有效,结果为True/False.但是,会发布以下警告.

Warning 1   'CommandLine.Parser.Parser(CommandLine.ParserSettings)' is obsolete: 'Use constructor that accepts Action<ParserSettings>.' 
Run Code Online (Sandbox Code Playgroud)

联机帮助将此作为使用该功能的示例.

new CommandLine.Parser(configuration: () => new CommandLine.ParserSettings(Console.Error))
Run Code Online (Sandbox Code Playgroud)

我尝试更改代码,但我没有让Lambda正确,我不知道如何让它工作.代码执行时,我只获取默认函数,我似乎无法更改Case Sensitive,Mutually Exclusive等...选项.

使用构造函数的行(来自内联IDE帮助)

bool Result = new CommandLine.Parser(configuration: (Settings) => new CommandLine.ParserSettings(UseCaseSensitive, EnableMutuallyExclusive, IgnoreUnknownOptions, null)).ParseArguments(Args, this);
Run Code Online (Sandbox Code Playgroud)

使用虚拟设置再次尝试:

bool Result = new CommandLine.Parser(configuration: (Settings) => new CommandLine.ParserSettings
     {
         CaseSensitive = UseCaseSensitive,
         IgnoreUnknownArguments = IgnoreUnknownOptions,
         MutuallyExclusive = EnableMutuallyExclusive
     }
).ParseArguments(Args, this);
Run Code Online (Sandbox Code Playgroud)

在线帮助没有跟上工具,我可以使用任何人可能有的指针.提前致谢...

clc*_*cto 10

查看源代码,构造函数运行Action传递给它创建的新设置:

public Parser(Action<ParserSettings> configuration)
{
    if (configuration == null) throw new ArgumentNullException("configuration");
    this.settings = new ParserSettings();
    configuration(this.settings);
    this.settings.Consumed = true;
}
Run Code Online (Sandbox Code Playgroud)

因此,Action<ParserSettings>您应该在参数上设置所需的值,而不是创建新设置(请记住,a Action<T>是一个函数的原型,它接受T并且不返回值):

var parser = new CommandLine.Parser( s => 
{
    s.CaseSensitive = UseCaseSensitive;
} );
Run Code Online (Sandbox Code Playgroud)

注意:我链接到的源代码似乎与您使用的版本不同,因为在我找到的源代码中Parser( ParserSettings )标记internal了,这意味着您甚至无法调用它,并且某些ParserSettings属性不会出现在我找到的版本中.但是,我相信这个答案也适用于您拥有的版本.