将十六进制字符串转换为动态基元类型

时间:2010-09-10 14:06:30

标签: c# .net

我有以下代码:

        string hexString = "0x00000004";
        Type hexType = typeof(Int32);

        object o = Convert.ChangeType(hexString, hexType);

一旦执行它就会抛出 System.FormatException ,显然,Convert.ChangeType无法使用十六进制值。

我的其他选择正在使用其中任何一种:

  • 的Int32 .Parse
  • 转换。的 ToInt32

但是,由于它们适用于特定类型,我需要使用开关 /反射来为正确的类型选择正确的函数。

我对这些选项中的任何一个都不是很兴奋。还有什么我可以做的吗?

1 个答案:

答案 0 :(得分:2)

由于十六进制通常仅用于整数,因此您可以parse将字符串设置为最大整数类型(Int64)并将change结果类型设置为所需类型:

string hexString = "deadcafebabe0000";
long hexValue = long.Parse(hexString, NumberStyles.AllowHexSpecifier);

Type hexType = typeof(Int32);
object o = Convert.ChangeType(hexValue, hexType);

(请注意,在将字符串传递给Parse方法之前,您需要删除0x前缀。)


Convert.ChangeType基本上是一大堆if (type == ...) ... else if (type == ...)语句。您可以创建一个字典,将所有整数类型映射到它们各自的Parse方法:

var dict = new Dictionary<Type, Func<string, object>>
{
    { typeof(byte),   s => byte.Parse(s, NumberStyles.AllowHexSpecifier) },
    { typeof(sbyte),  s => sbyte.Parse(s, NumberStyles.AllowHexSpecifier) },
    { typeof(short),  s => short.Parse(s, NumberStyles.AllowHexSpecifier) },
    { typeof(ushort), s => ushort.Parse(s, NumberStyles.AllowHexSpecifier) },
    { typeof(int),    s => int.Parse(s, NumberStyles.AllowHexSpecifier) },
    { typeof(uint),   s => uint.Parse(s, NumberStyles.AllowHexSpecifier) },
    { typeof(long),   s => long.Parse(s, NumberStyles.AllowHexSpecifier) },
    { typeof(ulong),  s => ulong.Parse(s, NumberStyles.AllowHexSpecifier) },
};

string hexString = (-5).ToString("X");
Type hexType = typeof(Int32);
object o = dict[hexType](hexString);