Convert a string containing a hexadecimal value starting with “0x” to an integer or long

后端 未结 4 2023
庸人自扰
庸人自扰 2020-12-05 18:23

How can I convert a string value like "0x310530" to an integer value in C#?

I\'ve tried int.TryParse (and even int.TryParse with Syste

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 18:42

    Direct from SHanselman, as pointed by Cristi Diaconescu, but I've included the main source code:

    public static T GetTfromString(string mystring)
    {
       var foo = TypeDescriptor.GetConverter(typeof(T));
       return (T)(foo.ConvertFromInvariantString(mystring));
    }
    

    The whole article deserves a closer look!

提交回复
热议问题