[英]How to define behavior that is executed in case of a command-parsing error using CommandLineUtils ExecuteAsync?
在執行時,我的程序需要兩個 arguments 它需要運行
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; }
我正在使用這個 package:
https://github.com/natemcmaster/CommandLineUtils
我想顯示一個消息框,以防程序運行的 arguments 太少/太多,或者 arguments 與所需的類型不匹配(1:字符串,2:整數)。
因為這不能通過簡單地包裝一個 try/catch 塊來實現:可以做到嗎?
解決這個問題出奇的簡單,我只是沒看到...
對於正在解決此問題的任何人:
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; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.