Try this:
(尝试这个:)
int x = Int32.Parse(TextBoxD1.Text);
or better yet:
(或更好:)
int x = 0;
Int32.TryParse(TextBoxD1.Text, out x);
Also, since Int32.TryParse
returns a bool
you can use its return value to make decisions about the results of the parsing attempt:
(同样,由于Int32.TryParse
返回bool
您可以使用其返回值来决定解析尝试的结果:)
int x = 0;
if (Int32.TryParse(TextBoxD1.Text, out x))
{
// you know that the parsing attempt
// was successful
}
If you are curious, the difference between Parse
and TryParse
is best summed up like this:
(如果您很好奇,最好将Parse
和TryParse
之间的区别总结如下:)
The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails.
(TryParse方法类似于Parse方法,但是如果转换失败,TryParse方法不会引发异常。)
It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed. (如果s无效且无法成功解析,则无需使用异常处理来测试FormatException。)
- MSDN (-MSDN)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…