当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > Convert.ToInt32与Int32.Parse区别及Int32.TryParse

ASP.NET
如何在ASP.NET中使用SmtpMail发送邮件
在VB.NET中利用Split和Replace函数计算字数
Attribute应用:简化ANF自定义控件初始化过程
ASP.NET 2.0移动开发入门之使用样式
ASP.NET 2.0中使用OWC生成图表
ASP.NET 2.0中控件的简单异步回调
一个无法捕获ADO.NET Dataset的内存错误
深入解读ADO.NET2.0的十大最新特性
.Net平台下的分布式缓存设计
ASP.NET全局异常处理浅析
ASP.NET 2.0中文验证码的实现
浅析.NET平台编程语言的未来走向
.net 框架程序设计收藏
使用ASP.NET MVC Futures 中的异步Action
详解.NET中的XmlReader与XmlWriter
关于.NET中的Server push技术
asp.net页面执行机制
对比JSP和ASP.NET的存储过程
.NET 4.0不会包含System.Shell.CommandLine
ASP.NET十个有效性能优化的方法

ASP.NET 中的 Convert.ToInt32与Int32.Parse区别及Int32.TryParse


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 137 ::
收藏到网摘: n/a

2个方法都可以把string转换为int,那么他们有什么区别?什么时候该用什么?性能如何。 其实在2.0里还有Int32.TryParse也实现了同样的效果。 using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string myString = "1234";
int myint = 0;
myint = Convert.ToInt32(myString);
Console.Write(myint+"\r\n ");
myint = Int32.Parse(myString);
Console.Write(myint+"\r\n ");
Int32.TryParse(myString, out myint);
Console.Write(myint+"\r\n");
}
}
}
表面上看,可见3个方法都实现了同样的效果!
那么我们把代码改一下:

//string myString = "1234";
string myString = null;
int myint = 0;
myint = Convert.ToInt32(myString);
Console.Write(myint+"\r\n");
myint = Int32.Parse(myString);
Console.Write(myint+"\r\n");
Int32.TryParse(myString, out myint);
Console.Write(myint+"\r\n");
运行结果:
Convert.ToInt32()在null时不抛异常而是返回0;
Int32.Parse()要抛异常;
Int32.TryParse()不抛异常,会返回true或false来说明解析是否成功,如果解析错误,调用方将会得到0值。
得出结论:
3个方法几乎没有差异!
如果要追求完美,那么可以参靠一下性能的差异:
Int32.TryParse()优于Int32.Parse()优于Convert.ToInt32()。
个人建议:.NET1.1下用Int32.Parse();.NET2.0用Int32.TryParse()。
为什么这样呢?
因为:Convert.ToInt32会把最终的解析工作代理给Int32.Parse,而Int32.Parse和Int32.TryParse则分别把解析工作直接代理给Number.ParseInt32和Number.TryParseInt32,前者在出现解析错误时会抛出异常,而后者则仅仅返回 false。