命令行解析器库:将十六进制字符串解析为 UInt32

Command Line Parser Library: Parse a hex string into UInt32

我有一个需要接收参数的控制台应用程序。该应用程序使用 Command Line Parser Library 来解析参数。

应用程序需要能够接收十六进制参数,并将它们转换为无符号整数。

例如,如果这是选项 class

public class CommandLineOptions
{
   [Option('l', "crcLocation", Required = false, HelpText = "Address where the CRC will be inserted.  Must be outside of the application image")]
   public UInt32 CrcLocation { get; set; }
}

那么该应用程序应该能够以

启动
app.exe -l 0x0000000F

因此将 CrcLocation 设置为 15

有没有办法让命令行解析器库从十六进制字符串转换为整数,或者应用程序是否需要手动执行此操作?

从库的源代码来看,它内部使用方法Convert.ChangeType进行转换,可惜不支持十六进制数。参见:https://github.com/gsscoder/commandline/blob/master/src/CommandLine/Core/TypeConverter.cs#L66

最好的办法是公开一个字符串并使用 UInt32.TryParse 和正确的 NumberStyles 标志来自己执行转换。