UInt抛出OverflowException

kus*_*lvm 1 c#

在向文本框输入负值时,我收到错误消息 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
Run Code Online (Sandbox Code Playgroud)

Iar*_*ica 6

发生这种情况是因为UInt32未签名.您应该使用Int32(无符号).

所以你的代码应该是这样的:

Int32 n = Convert.ToInt32(textBox2.Text);
if (n > 0)
  //code 
else
  //code
Run Code Online (Sandbox Code Playgroud)

但是,我宁愿这样说:

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
Run Code Online (Sandbox Code Playgroud)