【发布时间】:2018-10-13 02:23:51
【问题描述】:
我正在尝试在一个项目上编译以下代码
...
namespace Buzzbox
{
class Program
{
//Command line options through CommandLine: http://commandline.codeplex.com/
class Options
{
[Option('i', "input",
Required = true,
HelpText = "Path to input file to be Encoded, must be in hearthstonejson format.")]
public string InputFile { get; set; }
[Option('o', "output",
HelpText = "Output file path.",
Default = "output.txt")]
public string OutputFile { get; set; }
[Option('e', "encoding",
HelpText = "Which encoding format to use. Supported formats are scfdivineFormat and MtgEncoderFormat.",
Default = EncodingFormats.MtgEncoderFormat)]
public EncodingFormats EncodingFormat { get; set; }
[Option("shuffle-fields", Default = false,
HelpText = "Shuffles the fields of the output in supported Encoding Formats.")]
public bool ShuffleFields { get; set; }
[Option("shuffle-cards", Default = false,
HelpText = "Shuffles the the cards, randomizing the order of output.")]
public bool ShuffleCards { get; set; }
[Option("flavor-text", Default = false,
HelpText = "Include flavortext field.")]
public bool FlavorText { get; set; }
[Option("verbose", Default = false,
HelpText = "Output additional information. Exclusive with the --silent option.")]
public bool Verbose { get; set; }
[Option("silent", Default = false,
HelpText = "Never output anything but error messages. Exclusive with the --verbose option.")]
public bool Silent { get; set; }
}
private static void Main(string[] args)
{
//Parse Commandline options
var options = new Options();
var encode = new Encode
{
ShuffleFields = options.ShuffleFields,
IncludeFlavorText = options.FlavorText
};
//Only continue if commandline options fullfilled. CommandLine will handle helptext if something was off.
if (CommandLine.Parser.Default.ParseArguments(args,options))
{
//extra things
}
}
}
}
但我似乎只是让它工作,因为这条线有一个错误
CommandLine.Parser.Default.ParseArguments(args,options)
抛出异常
无法从“Buzzbox.Program.Options”转换为“System.Type”
它不允许我硬铸它,我还没有找到任何解决这个问题的方法,尽管我觉得解决方案可能相当简单,因为我发现其他人提到它,就像你可以投射一样就像这段代码一样,这里没有任何问题
http://simontimms.com/2014/07/09/parsing-command-line-arguments-in-c/
【问题讨论】:
-
它抛出的异常是什么?
-
已更新异常消息。
-
尝试两件事:1 - 将
public添加到Options类,2 - 将Options类移到Program类之外。 -
您可能需要在您的
options变量上使用typeof。CommandLine.Parser.Default.ParseArguments(args,typeof(options)) -
@ChrisDunaway 这不是有效的 C#。见docs.microsoft.com/en-us/dotnet/csharp/language-reference/…