问题描述
我使用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服务交给你以字符串格式为整数),你会使用<$c$c>Int32.Parse()$c$c>.
如果你从用户那里收集输入,你通常用<$c$c>Int32.TryParse()$c$c>,因为它可以让你对局势的更细粒度的控制,当用户在输入无效输入。
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.
<$c$c>Convert.ToInt32()$c$c>需要一个对象作为参数,我相信它会调用 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之间的主要区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!