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

ASP.NET
ASP.NET超凡的代码控制(二)
剖析ASP.NET下部构造(一)
剖析ASP.NET下部构造(二)
ASP.NET的Web controls(一)
ASP.NET的Web controls(二)
如何在页面上动态的生成 WebForm控件
再议正则表达式(这次是在asp.net 上的应用)
利用.NET框架简化发布和解决DLL Hell问题(1)
利用.NET框架简化发布和解决DLL Hell问题(2)
在ASP+中访问数据库
通过事例学习.net的WebForms技术(一)
通过事例学习.net的WebForms技术(二)
如何在aspx中得到在存储过程中的的数值(兼答jspfuns的问题)
如何得到一个汉字和字母组合的字符串的准确的长度(asp.net 版本的)
ASP+中取代ASP的RS(Remote Scripting)技术的Framework
通过事例学习.net的WebForms技术(三)
通过事例学习.net的WebForms技术(四)
通过事例学习.net的WebForms技术(五)
通过网络域名得到这台主机的IP地址
查看服务器磁盘、文件的aspx

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 225 ::
收藏到网摘: 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。