C#(int)中Convert、Parse、TryParse的区别
时间:2023-06-25 03:19:50
Convert.ToInt32、int.Parse(Int32.Parse)、int.TryParse、(int) 四者都可以解释为将类型转换为 int,那它们的区别是什么呢?
Convert.ToInt32 与 int.Parse 较为类似,实际上 Convert.ToInt32 内部调用了 int.Parse:
Convert.ToInt32 参数为 null 时,返回 0;
int.Parse 参数为 null 时,抛出异常。
Convert.ToInt32 参数为 "" 时,抛出异常;
int.Parse 参数为 "" 时,抛出异常。
Convert.ToInt32 可以转换的类型较多;
int.Parse 只能转换数字类型的字符串。
int.TryParse 与 int.Parse 又较为类似,但它不会产生异常,转换成功返回 true,转换失败返回 false。最后一个参数为输出值,如果转换失败,输出值为 0。
(int) 属 cast 转换,只能将其它数字类型转换成 int 类型,它不能转换字符串,比如下例就会失败:
string v = "1";
int n = (int)v;
int.TryParse 示例
int id = 1;
int.TryParse(Request.QueryString["id"], out id);
如果 QueryString 传入的 id 值为整数,那么 id 变量值就是该数值,如果传入的不是整数,那么 id 变量值就是 0(不是初始值 1)。
标签:Convert,Parse,TryParse
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
SpringBoot整合ES解析搜索返回字段问题
2023-01-26 21:39:53
.NET创建、删除、复制文件夹及其子文件的实例方法
2022-12-29 06:32:45
Android编程获取网络时间实例分析
2022-08-05 16:28:01
详解Java实现简单SPI流程
2022-12-11 16:02:23
C++编写DLL动态链接库的步骤与实现方法
2023-01-30 12:59:33
深入理解SpringMVC中央调度器DispatcherServlet
2023-03-11 08:54:48
![](https://img.aspxhome.com/file/2023/4/119184_0s.jpg)
JAVA中的字符串常量池使用操作代码
2021-11-24 02:00:57
![](https://img.aspxhome.com/file/2023/2/66932_0s.png)
Unity实现3D循环滚动效果
2023-04-22 14:05:47
![](https://img.aspxhome.com/file/2023/4/68624_0s.png)
java代码效率优化方法(推荐)
2023-05-26 01:42:32
Unity为软件添加使用有效期的具体步骤
2022-07-01 16:45:03
![](https://img.aspxhome.com/file/2023/1/113801_0s.png)
Java之线程编程的4种方法实现案例讲解
2021-11-18 18:40:46
C# 弹出窗口show()和showdialog()的两种方式
2022-05-08 17:12:36
![](https://img.aspxhome.com/file/2023/9/108729_0s.png)
netty pipeline中的inbound和outbound事件传播分析
2023-08-27 06:57:00
![](https://img.aspxhome.com/file/2023/5/58285_0s.png)
详解SpringBoot JPA常用注解的使用方法
2023-12-09 17:10:31
![](https://img.aspxhome.com/file/2023/5/72535_0s.png)
mybatis 对于生成的sql语句 自动加上单引号的情况详解
2023-09-21 15:25:00
![](https://img.aspxhome.com/file/2023/2/61342_0s.jpg)
SpringMVC编程使用Controller接口实现控制器实例代码
2023-02-01 02:03:36
详解MyBatis-Puls中saveBatch批量添加慢的问题
2021-10-14 02:36:27
![](https://img.aspxhome.com/file/2023/9/64369_0s.png)
C# 如何解析获取Url参数值
2022-07-03 01:00:52
C# 拷贝数组的几种方法(总结)
2023-09-14 06:50:17
Android 2.3.7.r1 camera录像过程中按menu菜单键时会停止录像
2023-06-13 01:46:10