【发布时间】:2021-09-03 15:06:48
【问题描述】:
当从double -> doublecasting 时,C# 编译器是否有任何理由发出 conv.r8 ?
这看起来完全没有必要(从 int -> int、char -> char 等进行转换)不会发出等效的转换指令(正如您在为 I2I() 方法生成的 IL 中看到的那样)。
class Foo
{
double D2D(double d) => (double) d;
int I2I(int i) => (int) i;
}
结果为:
.class private auto ansi '<Module>'
{
} // end of class <Module>
.class private auto ansi beforefieldinit Foo
extends [System.Private.CoreLib]System.Object
{
// Methods
.method private hidebysig
instance float64 D2D (
float64 d
) cil managed
{
// Method begins at RVA 0x2050
// Code size 3 (0x3)
.maxstack 8
IL_0000: ldarg.1
IL_0001: conv.r8
IL_0002: ret
} // end of method Foo::D2D
.method private hidebysig
instance int32 I2I (
int32 i
) cil managed
{
// Method begins at RVA 0x2054
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldarg.1
IL_0001: ret
} // end of method Foo::I2I
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x2057
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [System.Private.CoreLib]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method Foo::.ctor
} // end of class Foo
【问题讨论】:
-
我相信有一次它被用来强制 CPU 内部的
float80到float64但查看生成的 ASM 似乎并没有这样做 -
有趣.. 我什至没有费心去研究 ASM :)
-
我目前最好的猜测是老实说,它目前并未将其识别为可优化的。它认识到 int 不必强制转换并且可以安全地返回。如果你没有明确地投双倍,它不会发出一个 conv.r8 ... 可能值得在他们的 github 上询问
标签: c# compilation cil intermediate-language