当前位置: 移动技术网 > IT编程>开发语言>.net > Convert.ToInt32与Int32.Parse区别及Int32.TryParse

Convert.ToInt32与Int32.Parse区别及Int32.TryParse

2018年04月18日  | 移动技术网IT编程  | 我要评论

地底传奇,菩提树下之世间父母,美将请求闯黄岩岛

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。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网