System.Convert.ToInt VS(int)的 [英] System.Convert.ToInt vs (int)

查看:115
本文介绍了System.Convert.ToInt VS(int)的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到在另一篇文章,有人做了这样的:

I noticed in another post, someone had done something like:

double d = 3.1415;
int i = Convert.ToInt32(Math.Floor(d));



为什么他们使用convert函数,而不是:

Why did they use the convert function, rather than:

double d = 3.1415;
int i = (int)d;

有一个隐含的地板和转换。

which has an implicit floor and convert.

此外,更令人担心的,我在一些生产代码我读注意到:

Also, more concerning, I noticed in some production code I was reading:

double d = 3.1415;
float f = Convert.ToSingle(d);

是一样的:

float f = (float)d;



是所有那些否则隐式转换只是出于完整性Convert类,还是他们服务于一个目的?我可以理解,需要的ToString(),而不是休息。

Are all those otherwise implicit conversions just in the Convert class for completeness, or do they serve a purpose? I can understand a need for .ToString(), but not the rest.

推荐答案

铸造为int是隐含截断,不隐地板:

Casting to int is implicit truncation, not implicit flooring:

double d = -3.14;
int i = (int)d;
// i == -3



我选择Math.Floor或Math.Round到使我的意图更加明确。

I choose Math.Floor or Math.Round to make my intentions more explicit.

这篇关于System.Convert.ToInt VS(int)的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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