2
我使用Command Line Parser Library來解析命令行參數。如何使用Command Line Parser Library來防止錯誤發生?
我宣佈類Options
internal class Options
{
[Option('r', "read", Required = true,
HelpText = "Input file to be processed.")]
public string InputFile { get; set; }
[Option('f', "date from", Required = false,
HelpText = "Date from which get statistic.")]
public string DateFrom { get; set; }
[Option('t', "date to", Required = false,
HelpText = "Date to which get statistic.")]
public string DateTo { get; set; }
[Option('v', "verbose", DefaultValue = true,
HelpText = "Prints all messages to standard output.")]
public bool Verbose { get; set; }
[ParserState]
public IParserState LastParserState { get; set; }
[HelpOption]
public string GetUsage()
{
return HelpText.AutoBuild(this,
(HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));
}
}
而且這是我嘗試使用分析器:
private static void Main(string[] args)
{
Console.WriteLine("Hello and welcome to a test application!");
string filePath = string.Empty;
string fromDate = string.Empty, toDate = string.Empty;
DateTime dateTo, dateFrom;
Console.ReadLine();
var options = new Options();
if (CommandLine.Parser.Default.ParseArguments(args, options))
{
// Values are available here
if (options.Verbose) Console.WriteLine("Filename: {0}", options.InputFile);
if (string.IsNullOrWhiteSpace(options.InputFile))
{
filePath = ConfigurationManager.AppSettings["FilePath"];
if (string.IsNullOrWhiteSpace(filePath))
{
filePath = Directory.GetCurrentDirectory() + @"\Report.xlsx";
}
}
else
{
filePath = options.InputFile;
}
fromDate = string.IsNullOrWhiteSpace(options.DateFrom)
? ConfigurationManager.AppSettings["DateFrom"]
: options.DateFrom;
toDate = string.IsNullOrWhiteSpace(options.DateTo) ? ConfigurationManager.AppSettings["DateTo"] : options.DateTo;
}
else
{
return;
}
//其他代碼 }
但在一些錯誤的應用情況剛剛停止工作。
所以我想知道如何重複輸入值的第一步在出現錯誤的情況下。
while (!CommandLine.Parser.Default.ParseArguments(args, options)){...} - makes loop
類CommandLineOptions不是有效類。這是否意味着讀者會知道「明顯」的項目要取代/填充? –
CommandLineOptions是我作爲CommandLineParser類的功能封裝創建的類。 –
對不起,我的意思是說,當我將源代碼放入並將其放入Microsoft Visual Studio 2013時,它會識別源代碼不完整。我可以更具體。我也可能會誤解使用情況。 –