在文本框中输入负值时,我收到一个错误,显示为Unhandled Exception: System.OverflowException: Value was either too large or too small for a UInt32.
下面是我的代码:
UInt32 n = Convert.ToUInt32(textBox2.Text);
if (n > 0)
//code
else
//code发布于 2012-08-06 23:28:47
这是因为UInt32是未签名的。您应该改用Int32 (未签名)。
因此,您的代码应该如下所示:
Int32 n = Convert.ToInt32(textBox2.Text);
if (n > 0)
//code
else
//code然而,我更愿意这样说:
int n;
// TryParse method tries parsing and returns true on successful parsing
if (int.TryParse(textBox2.Text, out n))
{
if (n > 0)
// code for positive n
else
// code for negative n
}
else
// handle parsing error发布于 2012-08-06 23:30:30
输入负值意味着您正在尝试将负有符号值转换为无符号值,这会导致溢出异常。要么使用Int32,要么检查负数,并采取措施防止出错。
发布于 2012-08-06 23:30:30
不能将负值转换为无符号值。The MSDN特别声明你会得到一个异常。相反,请执行以下操作:
Int32 n= Convert.ToInt32(textBox2.Text);
UInt32 m = (UInt32) n;https://stackoverflow.com/questions/11831250
复制相似问题