位置:海鸟网 > IT > ASP.NET >

装箱、转型、方法调用他们究竟有什么区别?

以下为引用的内容:
装箱、转型、方法调用这些我们天天进行的日常工作之前到底有什么差别?

以下为引用的内容:
struct UserInfoStruct
 2{
 3   public int UserId;
 4   public string UserName;
 5}
 6class UserInfoClass
 7{
 8   private int UserId;
 9   private string UserName;
10}
11class Program
12{
13
14    static void Main(string[] args)
15    {
16         object objString = "abc";
17
18         string aString = (string)objString;
19         string bString = objString.ToString();
20         string cString = Convert.ToString(objString);
21
22         object objInt = 5;
23         int aInt = (int)objInt;
24         int bInt = Convert.ToInt32(objInt);
25
26         object objStruct = new UserInfoStruct();
27         UserInfoStruct aUserInfoStruct = (UserInfoStruct)objStruct;
28
29         object objClass = new UserInfoClass();
30         UserInfoClass aUserInfoClass = (UserInfoClass)objClass;
31     }
32}


前几天在群里聊天,有人问:

string aString = (string)objString;

string bString = objString.ToString();有什么区别,我当时就回答“一个是转型、一个是方法调用”,刚说完就觉得自己是在说废话,其实我也不知道内部到底发生了什么,如是就reflector,ILDASM,google一起上,现在把弄出来的结果整理了一下,share出来,并把相似的几个都集在一起讨论,由于我不懂WinDbg,所以无法深入,就浅尝辄止吧。

下面是main方法的IL代码:

以下为引用的内容:
1.method private hidebysig static void  Main(string[] args) cil managed
 2{
 3  .entrypoint
 4  // Code size       97 (0x61)
 5  .maxstack  1
 6  .locals init ([0] object objString,
 7           [1] string aString,
 8           [2] string bString,
 9           [3] string cString,
10           [4] object objInt,
11           [5] int32 aInt,
12           [6] int32 bInt,
13           [7] object objStruct,
14           [8] valuetype SomeKits.UserInfoStruct aUserInfoStruct,
15           [9] object objClass,
16           [10] class SomeKits.UserInfoClass aUserInfoClass,
17           [11] valuetype SomeKits.UserInfoStruct CS$0$0000)
18  IL_0000:  nop
19  IL_0001:  ldstr      "abc"
20  IL_0006:  stloc.0
21  IL_0007:  ldloc.0
22  IL_0008:  castclass  [mscorlib]System.String
23  IL_000d:  stloc.1
24  IL_000e:  ldloc.0
25  IL_000f:  callvirt   instance string [mscorlib]System.Object::ToString()
26  IL_0014:  stloc.2
27  IL_0015:  ldloc.0
28  IL_0016:  call       string [mscorlib]System.Convert::ToString(object)
29  IL_001b:  stloc.3
30  IL_001c:  ldc.i4.5
31  IL_001d:  box        [mscorlib]System.Int32
32  IL_0022:  stloc.s    objInt
33  IL_0024:  ldloc.s    objInt
34  IL_0026:  unbox.any  [mscorlib]System.Int32
35  IL_002b:  stloc.s    aInt
36  IL_002d:  ldloc.s    objInt
37  IL_002f:  call       int32 [mscorlib]System.Convert::ToInt32(object)
38  IL_0034:  stloc.s    bInt
39  IL_0036:  ldloca.s   CS$0$0000
40  IL_0038:  initobj    SomeKits.UserInfoStruct
41  IL_003e:  ldloc.s    CS$0$0000
42  IL_0040:  box        SomeKits.UserInfoStruct
43  IL_0045:  stloc.s    objStruct