简体   繁体   English

C#中的转换操作优先级

[英]Cast operation precedence in C#

Will the differences below matter significantly in C#? 在C#中,下面的差异是否显着?

int a, b;
double result;
result = (double)a / b;
result = a / (double)b;
result = (double)a / (double)b;

Which one do you use? 你用哪一个?

The cast will occur before the division. 演员将在分裂前发生。

In your examples, it doesn't matter which one you do as if one operand is a double, the runtime will cast/convert the other to a double as well. 在您的示例中,您执行哪一个操作并不重要,就像一个操作数是double一样,运行时也会将另一个操作数转换/转换为double。

This looks like a micro-optimization - not something worth worrying about or dealing with unless measurements show it is indeed a bottleneck. 这看起来像微优化 - 不值得担心或处理,除非测量表明它确实是一个瓶颈。

I do this: 我这样做:

result = (double)a / (double)b;

It may be strictly unnecessary, but generally I want to make sure that it will not do integer division, and I don't really care to remember the specific rules for this scenario, so it's easier (if a few more keystrokes) to be explicit. 它可能是完全没必要的,但一般来说我想确保它不会进行整数除法,并且我并不真正关心这个场景的具体规则,因此更容易(如果还有几次击键)要明确。

I do (double)a / b because I imagine an int to be something indivisible like a rock or something. 我做(double)a / b因为我想象一个int是不可分割的东西,如岩石或其他东西。 When cast to a double it becomes divisible, like a cake. 当铸成双倍时,它就像蛋糕一样可分割。 You can divide 3.0 cakes in four parts, but you can't divide three rocks in 4.0 parts. 你可以分为四个部分分开3.0个蛋糕,但你不能分成4.0个部分的三个岩石。 Or something. 或者其他的东西。 Do make any sense? 有意义吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM