【问题标题】:How to check if Parse(args) is true or false如何检查 Parse(args) 是真还是假
【发布时间】:2019-08-09 03:29:28
【问题描述】:

我的代码没有抛出任何错误。我使用了 NDesk 选项集并添加了 2 个字符串参数。我可以看到它在 args 中提取了正确的名称。但是当我使用 parse(args) 时,它不会引发错误。所以我假设它正在工作。

我正在尝试检查 p(args) 是真还是假。但是我不能对List<string>使用布尔表达式。

任何帮助我如何做到这一点。如果 parse 有正确的参数,我想要执行函数。

我的代码是这样的

private static Regex fileNamePattern = new Regex(@"^[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}[.]pdf$", RegexOptions.Compiled | RegexOptions.IgnoreCase); 

//missing method name
{
    string inputFile;
    string outputFile;
    var p = new OptionSet() {
        {"i"," pdf file",v=>inputFile=v},{"o","index file with kws",v=>outputFile=v},
    };

    Console.WriteLine($"args length: {args.Length}");
    Console.WriteLine($"args 0: {args[0]}");
    Console.WriteLine($"args 1: {args[1]}");

    p.Parse(args); //I would like to use this if(parse(args))
    {

    }
    // 
}

private static void UpdateImportIndexFile(string inputFile, string outputFile)
{
    using (var dip = File.CreateText(outputFile))
    {
        var match = fileNamePattern.Match(Path.GetFileName(MainFilePath));
        if (match.Success)
        {
            //create text file (outputfile);
        }
    }
}

【问题讨论】:

  • 请创建一个minimal reproducible example
  • 你为什么不使用 TryParse 而不是 Parse?
  • 我也有 TryParse。但在 ConsoleManger 中,它因错误而失败。
  • 错误是什么
  • 值不能为空。参数名称:输入为错误。

标签: c# ndesk.options


【解决方案1】:

由于p 是一个类的实例,并且parse 方法不支持返回以在某种意义上模拟TryParse 的功能,因此将您的解析包装在try 块中

try{
  val = p.Parse(args);
}catch(OptionException e){
  //if false
}

欲了解更多信息http://www.ndesk.org/doc/ndesk-options/NDesk.Options/OptionSet.html#M:NDesk.Options.OptionSet.Parse(System.Collections.Generic.IEnumerable{System.String})

【讨论】:

  • 你在在说什么?类没有have这样的方法。您是否阅读了该问题,或者这只是一个文本模板,可以粘贴到任何带有“Parse”一词的问题中?谁支持这三遍?
  • Parse 和 TryParse 原生于 c# @nvoigt docs.microsoft.com/en-us/dotnet/api/…
  • 但您确实意识到,在这种情况下,p 不是Int32,对吧?它甚至不是一个静态类名,而是一个名为 OptionSet 的类的类实例。
  • 我知道我会更新我的答案以反映@nvoigt
猜你喜欢
  • 2020-12-31
  • 2021-11-23
  • 1970-01-01
  • 2019-01-21
  • 2019-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-30
相关资源
最近更新 更多