int.Parse()和Convert.ToInt32之间的主要区别是什么

问题描述:


  • int.Parse() Convert.ToInt32()$ c之间的主要区别是什么$ c>?

  • 哪个是首选


  • 如果您有一个字符串,并且希望它始终是整数(例如,如果某些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.