int.Parse()和Convert.ToInt32之间的主要区别是什么 [英] What's the main difference between int.Parse() and Convert.ToInt32

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

问题描述


  • int.Parse() Convert.ToInt32()

  • 哪个是首选

推荐答案


  • 如果您有一个字符串,并且希望它始终是整数(例如,如果某些Web服务将字符串形式的整数传递给您),则d使用 Int32.Parse( )

    如果您要收集用户的输入,则表示通常使用 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 invalid input.

    Convert.ToInt32() 将一个对象作为其参数。 (有关其工作原理,请参见Chris S的答案)。

    Convert.ToInt32() takes an object as its argument. (See Chris S's answer for how it works)

    Convert.ToInt32()也不抛出 ArgumentNullException 当其参数为null时,方法与 Int32.Parse()相同。这也意味着 Convert.ToInt32()可能比 Int32.Parse()慢一点,尽管实践中,除非您在循环中进行大量迭代,否则您永远不会注意到它。

    Convert.ToInt32() also does not throw ArgumentNullException when its 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天全站免登陆