首页 > 解决方案 > 使用命令行解析参数

问题描述

我正在尝试使用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

标签: c#command-line-arguments

解决方案


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; }

}

推荐阅读