为什么向下拆箱会导致异常?

xpo*_*ort 1 c#

我不明白,为什么下面的代码会导致异常?

static class Utility<T>
{
    public static TReturn Change<TReturn>(T arg)
    {
        object temp = arg;
        return (TReturn)temp;
    }
}

class Program
{
    static void Main(string[] args)
    {
        int i = 100;

        try
        {
            short s = Utility<int>.Change<short>(i);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

我认为我的代码可以简化如下:

class Program
{
    static void Main(string[] args)
    { 
        int x = 100;
        object o = x;
        short s = (short)o;
    }
}
Run Code Online (Sandbox Code Playgroud)

Ðаn*_*Ðаn 5

您正在拆箱temp,这实际上是int直接进入 a short,这就是强制转换失败的原因。相反,您必须int首先拆箱到正确的类型 ( ),然后进行整数转换:

using System;

class Program
{
    static void Main(string[] args)
    {
        int i = 100;
        object temp = i;
        try
        {
            short s0 = (short)i;
            short s1 = (short)(int)temp;
            short s2 = (short)temp;
        }
        catch (Exception ex) { Console.WriteLine(ex); }
    }
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅 Eric Lippert 的表示和身份 表示和身份博客条目。