相关疑难解决方法(0)

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

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

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)

c#

1
推荐指数
1
解决办法
439
查看次数

标签 统计

c# ×1