从和到字符串的通用整数类型转换

Generic integer type conversion from and to string

我想将任何 integral 类型转换为十六进制字符串表示形式并返回。我想出了类似下面的东西,但它显然有错误。关于在 C# 中执行此操作的任何建议?提前致谢。

public class HexCnv<T>
{
    public static T ToIntType(string sInput)
    {
        return T.Parse(sInput.TrimStart('0', 'x'));
    }

    public static string ToStringType(T nInput)
    {
        return "0x" + nInput.ToString("X2");
    }
}

没有将泛型参数限制为整数类型的泛型约束,并且您不能在泛型类型上调用静态方法(如 Parse)。您可以使用隐式转换并在任何地方使用 long(或者 ulong),或者为每个整数类型提供重载 - 尽管您只需要 ToIntType 方法,因为 ToStringTypebyte 的结果与将 byte 转换为 long.

的结果相同

这个工作怎么样? (未测试)

public class HexCnv<T>
{
    public static readonly TypeCode typeCode = Type.GetTypeCode(typeof(T));
    
    public static T ToIntType(string sInput)
    {
        switch (typeCode)
        {
            case TypeCode.Int32:
               return Int32.Parse(sInput.TrimStart('0', 'x'));
            case TypeCode.Int64:
               return Int64.Parse(sInput.TrimStart('0', 'x'));
            ...
            ...
            ...
        }
        throw new ArgumentException(nameof(sInput));
    }

    public static string ToStringType(T nInput)
    {
        return "0x" + nInput.ToString("X2");
    }
}

我根据您的所有想法找到了解决方案,非常感谢。我已经测试了下面的代码,它按照我想要的方式工作,而且我用 generic 的感觉做了它;我可以测试其他方法来检查代码效率,但它对我有用,我希望这个想法对其他人有用:

public class HexCnv<T> 
{
    private MethodInfo _mParse;
    private MethodInfo _mToString;
    private T _value;
    private bool _isPrimitive;

    public HexCnv(T v)
    {
        Type t = typeof(T);

        _isPrimitive = t.IsPrimitive;
        _value = v;
        _mParse = t.GetMethod("Parse", new Type[] { typeof(string), typeof(NumberStyles) });
        _mToString = t.GetMethod("ToString", new Type[] { typeof(string) });
    }

    public HexCnv(string v)
    {
        Type t = typeof(T);

        _isPrimitive = t.IsPrimitive;
        _mParse = t.GetMethod("Parse", new Type[] { typeof(string), typeof(NumberStyles) });
        _mToString = t.GetMethod("ToString", new Type[] { typeof(string) });
        FromString(v);
    }

    private void FromString(string s)
    {
        if (_isPrimitive && _mParse != null)
            _value = (T)_mParse.Invoke(null, new object[] { s.TrimStart('0', 'x'), NumberStyles.HexNumber });
    }

    public new string ToString()
    {
        string sOut = string.Empty;

        if (_isPrimitive) sOut = "0x" + _mToString.Invoke(_value, new object[] { "x2" }).ToString();
        return sOut;
    }

    public static implicit operator T(HexCnv<T> v) { return v._value; }

    public static implicit operator HexCnv<T>(T v) { return new HexCnv<T>(v); }

    public static implicit operator HexCnv<T>(string v) { return new HexCnv<T>(v); }
}

如您所见,我更改了静态方法,使其可以通过简单的分配工作,请参阅下一个片段:

        HexCnv<short> mm = "0x1f55";

        Console.WriteLine("MM     = {0}", (int) mm);
        Console.WriteLine("MM-HEX = {0}", mm.ToString());

        //This produce the following result
        //  MM     = 8021
        //  MM-HEX = 0x1f55

        HexCnv<short> mm = "0x8f55"; //IDE show no errors on this, but
        HexCnv<short> mm = 0x8f55;   //It'll give an error on this expression,  
                                     //cuz the number is higher than "short"