C# 为什么;0x5";是否未解析为有效的十六进制数?
我试图检查字符串是否包含有效的十六进制数 我正在使用中记录的方法 使用以下代码:C# 为什么;0x5";是否未解析为有效的十六进制数?,c#,C#,我试图检查字符串是否包含有效的十六进制数 我正在使用中记录的方法 使用以下代码: using System; using System.Collections.Generic; public class Program { public static void Main() { int temp; bool b = int.TryParse("0x5", System.Globalization.NumberStyles.HexNumber, S
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
int temp;
bool b = int.TryParse("0x5", System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture, out temp);
System.Console.Write("{0} : {1}", b, temp);
}
}
我在输出中得到:False:0
这里怎么了?来自:
AllowHexSpecifier
指示数字字符串表示十六进制值。有效的十六进制值包括数字0-9以及十六进制数字A-F和A-F使用此样式解析的字符串不能以“0x”或“&h”作为前缀。使用AlloweXSpecifier样式解析的字符串将始终解释为十六进制值。唯一可以与AllowWhexSpecifier组合的标志是AllowReadingWhite和AllowTrailingWhite。NumberStyles枚举包括一个复合样式HexNumber,它由这三个标志组成
(Emphasis mine。)它似乎无法解析“0x”部分,如果您只编写例如int.TryParse(“5”…)的代码,那么它就可以工作(同样int.TryParse(“A”…)也可以工作)。对我来说不好:)。。。我最终使用正则表达式来检测。感谢您,尽管它的名称,
allowehexspecifier
不允许任何十六进制说明符。它只是把这个东西解释成十六进制-/