类型转换错误
问题描述:
答
int age = int.Parse(txtAge.Text);
答
尝试
int age;
bool result = Int32.TryParse(txtAge.Text, out age);
if (result)
{
// Parse succeeded and get the result in age
}
else
{
// Parse failed
}
见Int32.TryParse Method (String, Int32)
The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails. 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.
答
当然可以” t,int和string是两种完全不同的类型。然而,最简单的解决办法是:
int age = Int32.Parse(txtAge.Text);
更安全的是:
int age;
Int32.TryParse(txtAge.Text, out age);
注意,你应该检查是从'TryParse'返回'bool',和国际海事组织这是更为常见看到'int'而不是'Int32'(尽管如此)。 – 2010-01-14 06:23:37
第一个我可以同意,第二个(int与Int32)取决于公司内的编程惯例。我的公司约定状态:使用int表示声明和显式转换,Int32用于静态方法调用。 但当然这是所有政策的主观:)。 – Webleeuw 2010-01-14 06:45:56