您可以使用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