这更像是一个学术问题,而不是我真正担心性能的问题。我只是真的很好奇而已。在我公认有限的编程经验中,我还了解到编译器只有大约一半的时间是聪明的。
我有一个静态类,其中定义了一个常量 int,我需要将该常量除以另一个整数。现在,我需要一个从该除法返回的浮点值,所以我不能只将它们都保留为整数。
const int CONSTANTINTEGER = 69;
int integer = 0;
float floatValue = 0f;
for(integer = 0; integer < CONSTANTINTEGER; integer++) {
float floatValue = integer / (float)CONSTANTINTEGER;
//use floatValue for algorithm.....
}
现在,我的问题是:编译器是否足够聪明,可以创建一个常量 float 来代替 (float)CONSTANTINTEGER,或者它是否在每个循环中都将整数转换为 float ?
请您参考如下方法:
语言规范可以帮助我们解决这个问题。 C# 5 规范的第 7.19 节指出:
A constant expression must be the null literal or a value with one of the following types: sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, object, string, or any enumeration type. Only the following constructs are permitted in constant expressions:
- ...
- Cast expressions, provided the target type is one of the types listed above.
...
Whenever an expression fulfills the requirements listed above, the expression is evaluated at compile-time. This is true even if the expression is a sub-expression of a larger expression that contains non-constant constructs.
您还可以通过查看 IL 来验证这一点,在本例中它具有:
IL_000a: ldc.r4 69.
当它为除法运算加载除数时。
