UInt32.TryParse()十六进制数不起作用

S.C*_*sen 14 c# tryparse

由于某种原因,以下C#控制台程序始终输出:

32

wtf = 0

我究竟做错了什么?

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Convert.ToUInt32("0x20", 16));
            UInt32 wtf = 0;
            Console.WriteLine(UInt32.TryParse("0x20",
                              NumberStyles.HexNumber, // I've tried also AllowHexSpecifier
                              CultureInfo.InvariantCulture,  // I've also tried CurrentCulture
                              out wtf));
            Console.WriteLine("wtf={0}", wtf);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 23

您需要删除"0x"前缀.请参阅此博客条目

  • 哇.这接近我会说的一个错误. (4认同)
  • 来自 [NumberStyles Enumeration](http://msdn.microsoft.com/en-us/library/system.globalization.numberstyles%28v=vs.110%29.aspx),**AllowHexSpecifier**:*解析的字符串使用此样式不能以“0x”或“&h”为前缀。* (2认同)

小智 7

// stupid but effective way to improve the parsing
char[] _trim_hex = new char[] {'0','x'};
int temp;

if (int.TryParse(value.TrimStart(_trim_hex), NumberStyles.HexNumber, null, out temp))
{
    // temp is good
}
Run Code Online (Sandbox Code Playgroud)