简体   繁体   English

转换值类型常量

[英]Casting value-type constants

This is more of an academic question than one where I'm really worried about the performance. 这不是我真正担心性能的问题,而是更多的学术问题。 I'm just really curious is all. 我真的很好奇。 I've also learned in my, admittedly limited, programming experience that the compiler is only smart about half the time. 我还从有限的编程经验中学到,编译器只有一半的时间才是明智的。

I have a static class where a constant int is defined and I need to divide that constant by another integer. 我有一个静态类,其中定义了一个常量int ,我需要将该常量除以另一个整数。 Now, I need a float value returned from that division, so I can't just leave them both as integers. 现在,我需要从该除法返回的浮点值,所以不能只将它们都保留为整数。

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.....
}

Now, my question: Is the compiler smart enough to create a constant float in place of the (float)CONSTANTINTEGER or does it cast the integer to a float every single loop? 现在,我的问题是:编译器是否足够聪明,可以代替(float)CONSTANTINTEGER创建一个常量浮点数,还是将整数转换为每个循环的浮点数?

The language specification helps us out here. 语言规范在这里帮助了我们。 Section 7.19 of the C# 5 spec states: 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. 常量表达式必须是空文字或具有以下类型之一的值:sbyte,byte,short,ushort,int,uint,long,ulong,char,float,double,decimal,bool,object,string或任何其他类型枚举类型。 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. 即使表达式是包含非恒定构造的较大表达式的子表达式,也是如此。

You can also validate this by looking at the IL, which in this case has: 您还可以通过查看IL来验证这一点,在这种情况下,它具有:

IL_000a:  ldc.r4     69.

when it's loading the divisor for the division operation. 在加载除法运算的除数时。

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

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