如何使用 CommandLineUtils ExecuteAsync 定义在出现命令解析错误时执行的行为?

How to define behavior that is executed in case of a command-parsing error using CommandLineUtils ExecuteAsync?

执行时,我的程序需要两个参数 运行

static Task<int> Main(string[] args)
{
   return CommandLineApplication.ExecuteAsync<MyUpdateService>(args);
}

[Argument(0, Description = "Filepath")]
     
private string Filepath { get; }

[Argument(1, Description = "UpdateMode")]

private int Mode { get; }

我正在使用这个包:

https://github.com/natemcmaster/CommandLineUtils

我想显示一个消息框,以防程序 运行 参数太少/太多,或者参数与所需类型不匹配(1:字符串,2:整数)。

因为这不能通过简单地在其周围包裹一个 try/catch-block 来实现:可以做到吗?

这个问题的解决方案非常简单,我只是没看到...

对于正在解决此问题的任何人:

public static Task<int> Main(string[] args)
{
    try
    {
        //if program is run without command-line arguments
        if (args == null || args.Length == 0)
        {
            throw new ArgumentNullException();
        }
        //if program is run with more or less than 2 arguments
        else if (args.Length != 2)
        {
            throw new ArgumentOutOfRangeException();
        }
        //if - for example - the second argument cannot be parsed to an int
        else if (!int.TryParse(args[1], out int result))
        {
            throw new ArrayTypeMismatchException();
        }
    }
    catch (Exception ex)
    {
        string errorMsg = "This app cannot be executed direclty.";

        if (ex is ArgumentOutOfRangeException || ex is ArrayTypeMismatchException)
        {
            errorMsg = "Exception error: This app needs a different set of arguments to execute.";
        }
        new CustomMessageBox().Show(errorMsg);
        return Task.FromResult(1);
    }

    return CommandLineApplication.ExecuteAsync<MyUpdateService>(args);
}

[Required, Argument(0, Description = "Filepath")]

private string IniFilepath { get; }

[Required, Argument(1, Description = "UpdateMode")]

private int Mode { get; }