Convert.ToInt32与Int32.Parse区别及Int32.TryParse
Convert.ToInt32与Int32.Parse区别及Int32.TryParse
发布时间:2016-12-29 来源:查字典编辑
摘要:usingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespace...

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+"rn ");

myint = Int32.Parse(myString);

Console.Write(myint+"rn ");

Int32.TryParse(myString, out myint);

Console.Write(myint+"rn");

}

}

}

表面上看,可见3个方法都实现了同样的效果!

那么我们把代码改一下:

//string myString = "1234";

string myString = null;

int myint = 0;

myint = Convert.ToInt32(myString);

Console.Write(myint+"rn");

myint = Int32.Parse(myString);

Console.Write(myint+"rn");

Int32.TryParse(myString, out myint);

Console.Write(myint+"rn");

运行结果:

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。

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新asp.net教程学习
热门asp.net教程学习
编程开发子分类