何时使用Cast或Convert [英] When to use a Cast or Convert
问题描述
我很想知道一个演员说一个int与使用Convert.toInt32()之间的区别是什么。使用一个是否有某种性能上的提高?
I am curious to know what the difference is between a cast to say an int compared to using Convert.toInt32(). Is there some sort of performance gain with using one?
每种情况都应该使用。目前我更倾向于使用转换,但我没有理由去任何一种方式。在我看来,我看到他们都完成了同样的目标。
Also which situations should each be used for. Currently I'm more inclined to use Convert but I don't have a reason to go either way. In my mind I see them both accomplishing the same goal.
推荐答案
查看在另一个论坛上强制转换。
答案
下面的Convert.ToInt32(String,IFormatProvider)调用Int32.Parse。所以唯一的区别是,如果一个空字符串
被传递给Convert它返回0,而Int32.Parse引发一个
ArgumentNullException。这是真正的选择,无论你
使用。
The Convert.ToInt32(String, IFormatProvider) underneath calls the Int32.Parse. So the only difference is that if a null string is passed to Convert it returns 0, whereas Int32.Parse throws an ArgumentNullException. It is really a matter of choice whichever you use.
我个人使用,并且倾向于使用TryParse函数,如 System.Int32.TryParse()
Personally, I use neither, and tend to use the TryParse functions, as in System.Int32.TryParse()
这篇关于何时使用Cast或Convert的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!