如何将 String 转换为 Int?

编程入门 行业动态 更新时间:2024-10-17 11:28:11
本文介绍了如何将 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 }

如果你好奇的话,Parse 和 TryParse 的区别最好总结如下:

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?

本文发布于:2023-06-08 21:30:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/589406.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   如何将   String   Int

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!