首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

Convert 会不会以致装箱和折箱

2013-09-08 
Convert 会不会导致装箱和折箱 string strValue 10 int iValue Convert.ToInt16(strValue)[解决办

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)


{
    return Parse(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}

private static short Parse(string s, NumberStyles style, NumberFormatInfo info)
{
    int num = 0;
    try
    {
        num = Number.ParseInt32(s, style, info);
    }
    catch (OverflowException exception)
    {
        throw new OverflowException(Environment.GetResourceString("Overflow_Int16"), exception);
    }
    if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
    {
        if ((num < 0) 
[解决办法]
 (num > 0xffff))
        {
            throw new OverflowException(Environment.GetResourceString("Overflow_Int16"));
        }
        return (short) num;
    }
    if ((num < -32768) 
[解决办法]
 (num > 0x7fff))
    {
        throw new OverflowException(Environment.GetResourceString("Overflow_Int16"));
    }
    return (short) num;
}
 

热点排行