您可以使用Visual Studio附带的ILDASM。它是一个IL反汇编程序。
下面是代码:
public void Foo()
{
object myObj = "abc";
string myStr = (string)myObj;
}
这里是我的了:
.method public hidebysig instance void Foo() cil managed
{
// Code size 15 (0xf)
.maxstack 1
.locals init ([0] object myObj,
[1] string myStr)
IL_0000: nop
IL_0001: ldstr "abc"
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: castclass [mscorlib]System.String
IL_000d: stloc.1
IL_000e: ret
} // end of method ShowWhatCastIs::Foo
随着toString()方法:
public void Foo2()
{
object myObj = "abc";
string myStr = myObj.ToString();
}
的IL是:
.method public hidebysig instance void Foo2() cil managed
{
// Code size 15 (0xf)
.maxstack 1
.locals init ([0] object myObj,
[1] string myStr)
IL_0000: nop
IL_0001: ldstr "abc"
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: callvirt instance string [mscorlib]System.Object::ToString()
IL_000d: stloc.1
IL_000e: ret
} // end of method ShowWhatCastIs::Foo2
当您将字符串“abc”存储在位置0中时,则会加载位置0,使用“cast class [mscorlib] System.String”强制转换该值,然后将该值存储到位置1
当您致电.ToString()它虚拟地在字符串上调用System.Object.ToString()。 toString()方法在System.String
定义下面是System.String.ToString()的ILDASM:
.method public hidebysig virtual instance string
ToString() cil managed
{
.custom instance void System.Runtime.TargetedPatchingOptOutAttribute::.ctor(string) = (01 00 3B 50 65 72 66 6F 72 6D 61 6E 63 65 20 63 // ..;Performance c
72 69 74 69 63 61 6C 20 74 6F 20 69 6E 6C 69 6E // ritical to inlin
65 20 61 63 72 6F 73 73 20 4E 47 65 6E 20 69 6D // e across NGen im
61 67 65 20 62 6F 75 6E 64 61 72 69 65 73 00 00) // age boundaries..
.custom instance void __DynamicallyInvokableAttribute::.ctor() = (01 00 00 00)
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ret
} // end of method String::ToString
它只返回本身。
你看过制作的这个演员阵容吗? – Oded
我想严格来说,一个强制转换将是'string myStr = myObj'作为字符串;'也许答案可以包括差异(就CLR而言......) – EtherDragon
@EtherDragon - 'as'更像是一个“尝试强制转换”。 OP的语法当然是一个演员。 – Oded