如何将 String 转换为 Int? [英] How can I convert String to Int?

查看:50
本文介绍了如何将 String 转换为 Int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 TextBoxD1.Text,我想将其转换为 int 以将其存储在数据库中.

I have a TextBoxD1.Text and I want to convert it to an int to store it in a database.

我该怎么做?

推荐答案

试试这个:

int x = Int32.Parse(TextBoxD1.Text);

或者更好:

int x = 0;

Int32.TryParse(TextBoxD1.Text, out x);

此外,由于 Int32.TryParse 返回一个 bool 你可以使用它的返回值来决定解析尝试的结果:

Also, since Int32.TryParse returns a bool you can use its return value to make decisions about the results of the parsing attempt:

int x = 0;

if (Int32.TryParse(TextBoxD1.Text, out x))
{
    // you know that the parsing attempt
    // was successful
}

如果你好奇的话,ParseTryParse 的区别最好总结如下:

If you are curious, the difference between Parse and TryParse is best summed up like this:

TryParse 方法就像 Parse方法,TryParse 方法除外不抛出异常,如果转换失败.它消除了需要使用异常处理来测试对于事件中的 FormatException那 s 是无效的,不能是成功解析.- MSDN

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. - MSDN

这篇关于如何将 String 转换为 Int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆