使用命令行解析参数

Using Command Line to parse arguments

我正在尝试使用 CommandLine 来启用我的控制台应用程序的解析参数。我认为我没有正确使用它。我正在尝试学习如何创建不同的选项,例如 -s 代表符号,-d 代表日期。这是我的尝试:

public interface ICommandLineOption
    {
        string WhichOption { get; }
    }

[Verb("symbol", HelpText = "Symbol to test")]
public class SymbolCommand : ICommandLineOption
{
    public string WhichOption { get { return "Symbol"; } private set { } }

    [Option('s', "symbol", Required = true, HelpText = "Symbol To run backtest")]
    public string Symbol { get; set; }
    
}

[Verb("begin", HelpText = "Start date of test")]
public class BeginDateCommand : ICommandLineOption
{
    public string WhichOption { get { return "BeginDate"; } private set { } }

    [Option('d', "date", Required = true, HelpText = "Date to begin run of backtest")]
    public System.DateTime BeginDate { get; set; }
    
}

static void Main(string[] args)
{
    Parser.Default.ParseArguments<ICommandLineOption>(args).WithParsed<ICommandLineOption>(o =>
    {
        switch (o.WhichOption)
        {
            case "Symbol":
                {
                    var comm = o as SymbolCommand;
                    Console.WriteLine(comm.Symbol);
                    break;
                }
            case "BeginDate":
                {
                    var comm = o as BeginDateCommand;
                    Console.WriteLine(comm.BeginDate);
                    break;
                }
            default:
                break;
        }
    });
}

但这行不通:

Exception thrown: 'System.InvalidOperationException' in CommandLine.dll
An unhandled exception of type 'System.InvalidOperationException' occurred in CommandLine.dll
Type ICommandLineOption appears to be immutable, but no constructor found to accept values
static void Main(string[] args)
{
       Parser.Default.ParseArguments<CommandLineOptions>(args)
       .WithParsed<CommandLineOptions>(o =>
       {
                Console.WriteLine(o.Symbol);
                Console.WriteLine(o.Date);
       });
     ...
}

public class CommandLineOptions
{
    [Option('s', "symbol", Required = true, HelpText = "Symbol To run backtest")]
    public string Symbol { get; set; }

    [Option('d', "date", Required = true)]
    public string Date { get; set; }

}