日期:2014-05-17  浏览次数:20833 次

Convert 会不会导致装箱和折箱
 string strValue = "10";
 int iValue = Convert.ToInt16(strValue);

------解决方案--------------------
针对楼主的问题,这里没有发生.....

查看IL如下:
string value = "10";
            int iValue = Convert.ToInt16(value);

            string value2 = "10";
            object obj = value2;
            int objValue = (int)obj;

1.编译exe
2.运行ildasm(2012 版):start -> vs -> visual studio Tools -> developer command prompt for vs2012
3.运行命令:ildasm D:\A.exe       //exe 路径
4.在IL DASM 里,双击Main,可以看到:
IL_0000:  nop
  IL_0001:  ldstr      "10"
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  call       int16 [mscorlib]System.Convert::ToInt16(string)
  IL_000d:  stloc.1
  IL_000e:  ldstr      "10"
  IL_0013:  stloc.2
  IL_0014:  ldloc.2
  IL_0015:  stloc.3
  IL_0016:  ldloc.3
  IL_0017:  unbox.any  [mscorlib]System.Int32
  IL_001c:  stloc.s    V_4
  IL_001e:  ret


在0008,可以看到调用了Convert的ToInt方法,
在0017处,发生了拆箱....

------解决方案--------------------
给你贴源码

public static short ToInt16(string value)
{
    if (value == null)
    {
        return 0;
    }
    return short.Parse(value, CultureInfo.CurrentCulture);
}

public static short Parse(string s, IFormatProvider provider)