Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C语言中将常量转换赋值给变量#_C#_Variables_Casting_Compiler Optimization_Var - Fatal编程技术网

C# 在C语言中将常量转换赋值给变量#

C# 在C语言中将常量转换赋值给变量#,c#,variables,casting,compiler-optimization,var,C#,Variables,Casting,Compiler Optimization,Var,考虑到以下情况,C#编译器有多聪明: float a = 1; //A var b = 1f; //B var c = (float)1; //C - Is this line equivalent to A and B? var d = Convert.ToSingle(1); //D - Is this line equivalent to A and B? 据我所知,A和B在编译后是等价的。其他线路呢 C和D是否在编译时优化为与A和B等效,还是只在运行时分配,从而导致更多的处理来执行分配

考虑到以下情况,C#编译器有多聪明:

float a = 1; //A
var b = 1f; //B
var c = (float)1; //C - Is this line equivalent to A and B?
var d = Convert.ToSingle(1); //D - Is this line equivalent to A and B?
据我所知,A和B在编译后是等价的。其他线路呢

C和D是否在编译时优化为与A和B等效,还是只在运行时分配,从而导致更多的处理来执行分配

我认为铸造(C)必须优化,函数(D)不能优化


在任何情况下,如何使用VS2012调查和比较生成的汇编代码?

前三行是等效的;事实上,它们编译成相同的IL(至少使用我使用的.NET4编译器)

第四个是通过调用方法执行的运行时转换,这是一个完全不同的beast

关于检查生成的IL,请查看

我如何使用 VS2012

“转到部件”(或按CTRL+ALT+D)

答案如下

            float x = 1; //A
00000061  fld1 
00000063  fstp        dword ptr [ebp-40h] 
            var x1 = 1f; //B
00000066  fld1 
00000068  fstp        dword ptr [ebp-44h] 
            var x2 = (float)1; //C - Is this line equivalent to A and B?
0000006b  fld1 
0000006d  fstp        dword ptr [ebp-48h] 
            var x3= Convert.ToSingle(1); //D - Is this line equivalent to A and B?
00000070  mov         ecx,1 
00000075  call        5FB7A2DC 
0000007a  fstp        dword ptr [ebp-50h] 
0000007d  fld         dword ptr [ebp-50h] 
00000080  fstp        dword ptr [ebp-4Ch] 

我很确定
var
是在编译时计算的(类型至少为)。与
dynamic
1)相反,当您重新定义
x
时,代码不会编译。为每行指定不同的变量名。2) 修复#1后,程序将可编译。与其问我们关于a、b、c和d的问题,为什么不自己编译程序并找出答案呢?这比在这里提问更快更容易。@Jon是的,已经编辑过;)对不起,我没有提到这些行不是程序的一部分。我只是在比较两种方法。答案很好,我使用LINQPad,但我从未注意到这个特性,它非常容易使用。非常感谢。我也是,vs2012+1(不需要外部工具)