何时使用 Cast 或 Convert [英] When to use a Cast or Convert

查看:19
本文介绍了何时使用 Cast 或 Convert的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很想知道与使用 Convert.ToInt32() 相比,转换表示 int 有什么区别.使用它是否有某种性能提升?

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?

还有应该分别用于哪些情况?目前我更倾向于使用 Convert 但我没有理由选择任何一种方式.在我看来,我认为他们都实现了相同的目标.

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.

推荐答案

参见 转换和转换之间的区别 在另一个论坛上

See Diff Between Cast and Convert on another forum

Convert.ToInt32(String, IFormatProvider) 下面调用Int32.Parse(阅读备注).
所以唯一的区别是,如果传递一个空字符串,它返回 0,而 Int32.Parse 抛出一个 ArgumentNullException.
无论您使用哪个,这真的是一个选择问题.

The Convert.ToInt32(String, IFormatProvider) underneath calls the Int32.Parse (read remarks).
So the only difference is that if a null string is passed 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 (e.g. System.Int32.TryParse()).

顶部链接已损坏,请参阅此答案 在 StackOverflow 上.

Link on top is broken, see this answer on StackOverflow.

这篇关于何时使用 Cast 或 Convert的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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