uint color;
bool parsedhex = uint.TryParse(TextBox1.Text, out color);
//where Text is of the form 0xFF0000
if(parsedhex)
//...
不起作用。我究竟做错了什么?
uint color;
bool parsedhex = uint.TryParse(TextBox1.Text, out color);
//where Text is of the form 0xFF0000
if(parsedhex)
//...
不起作用。我究竟做错了什么?
Answers:
尝试
Convert.ToUInt32(hex, 16) //Using ToUInt32 not ToUInt64, as per OP comment
Convert.ToUInt32将把“ 0x”前缀作为输入的一部分来处理。
您可以使用重载TryParse(),该重载将NumberStyle参数添加到TryParse提供解析十六进制值的调用中。使用NumberStyles.HexNumber此功能,您可以将字符串作为十六进制数字传递。
注:这个问题NumberStyles.HexNumber是,它不支持带有前缀解析值(即0x,&H或者#,所以你必须试图解析值之前剥离其关闭)。
基本上,您可以这样做:
uint color;
var hex = TextBox1.Text;
if (hex.StartsWith("0x", StringComparison.CurrentCultureIgnoreCase) ||
hex.StartsWith("&H", StringComparison.CurrentCultureIgnoreCase))
{
hex = hex.Substring(2);
}
bool parsedSuccessfully = uint.TryParse(hex,
NumberStyles.HexNumber,
CultureInfo.CurrentCulture,
out color);
有关如何使用NumberStyles枚举的示例,请参阅本文:http : //msdn.microsoft.com/zh-cn/library/zf50za27.aspx
这是一个try-parse样式函数:
private static bool TryParseHex(string hex, out UInt32 result)
{
result = 0;
if (hex == null)
{
return false;
}
try
{
result = Convert.ToUInt32(hex, 16);
return true;
}
catch (Exception exception)
{
return false;
}
}