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;
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
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;
}