最新int.Parse()和Convert.ToInt32之间的主要区别 [英] Whats the main difference between int.Parse() and Convert.ToInt32

查看:114
本文介绍了最新int.Parse()和Convert.ToInt32之间的主要区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C#,并想知道这两个哪一个之间的主要区别是preferred编码时使用。

I am using C#,and wanted to know the main difference between the two and which one is preferred to use while coding.

推荐答案


  • 如果你有一个字符串,你希望它永远是一个整数(比方说,如果一些Web服务交给你以字符串格式为整数),你会使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.int32.parse.aspx\"><$c$c>Int32.Parse().

如果你从用户那里收集输入,你通常用<一个href=\"http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx\"><$c$c>Int32.TryParse(),因为它可以让你对局势的更细粒度的控制,当用户在输入无效输入。

If you're collecting input from a user, you'd generally use Int32.TryParse(), since it allows you more fine-grained control over the situation when the user enters in invalid input.

<一个href=\"http://msdn.microsoft.com/en-us/library/System.Convert.ToInt32.aspx\"><$c$c>Convert.ToInt32()需要一个对象作为参数,我相信它会调用 Int32.TryParse()当它发现作为参数的对象是一个字符串。

Convert.ToInt32() takes an object as its argument, and I believe it invokes Int32.TryParse() when it finds that the object taken as the argument is a string.

Convert.ToInt32()也不会抛出 ArgumentNullException 时,它的参数为空的方式 Int32.Parse()一样。这也意味着, Convert.ToInt32()可能比 Int32.Parse慢一丁点(),但在实践中,除非你正在做在一个循环中一个非常大的迭代次数,你永远也不会注意到它。

Convert.ToInt32() also does not throw ArgumentNullException when it's argument is null the way Int32.Parse() does. That also means that Convert.ToInt32() is probably a wee bit slower than Int32.Parse(), though in practice, unless you're doing a very large number of iterations in a loop, you'll never notice it.

这篇关于最新int.Parse()和Convert.ToInt32之间的主要区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆