且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将字符串转换为Int

更新时间:2023-02-14 09:37:11

而不仅仅是转换值,***是使用TryParse来测试是否可以转换值,如果可以,它将被转换。看一下 Int.TryParse [ ^ ]和 double.TryParse [ ^ ]



类似

Instead of just converting the values it would be better to use TryParse to test if the value can be converted and if it can, it'll be converted. Have a look at Int.TryParse[^] and double.TryParse[^]

Something like
double num2;
if (!double.Parse(TextBox2.Text, out num2)) {
   System.Diagnostics.Debug.WriteLine(string.Format("{0} is not a double.", TextBox2.Text));
   return;
}





请注意,您最初有一个额外的分号



Note that you originally had an extra semicolon in

double num2 = double.TryParse(TextBox2.Text;);


您有两个选择:按照建议使用 TryParse 方法,或处理抛出的异常。无论哪种方式,您都应明确处理可能的无效用户输入。例如,您可以显示一个消息框,说明给定字段的格式要求是什么。
You have two options: use, as suggested, the TryParse methods, or handle the thrown exceptions. In either ways you should explicitely deal with possible invalid user inputs. For instance, you may show a message box explaining what are the format requirements for the given field.


int value;
if (Int32.TryParse("50", out value))
    Console.WriteLine(value);
else
    Console.WriteLine("Failed to parse the string value to integer.");