我注意到在另一篇文章,有人做了这样的:
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)的
发布评论