c# - 为什么下投拆箱会导致异常?

标签 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);
        }
    }
}


编辑:

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

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

最佳答案

您要将真正是tempint直接拆箱到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); }
    }
}


编辑:根据其他人的建议,请参阅Eric Lippert的Representation and Identity博客条目,以获取许多详细信息。

关于c# - 为什么下投拆箱会导致异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3911293/

相关文章:

c# - QuickBooks 自定义应用程序部署

c# - 具有许多异步插入的 MySQL 连接器池

c# - MongoDB 中的多重排序规则

c# - Quartz.Net 工作进度

c# - 将 EAP 包装在任务中

C# 创建缓冲区溢出

c# - 使用 GitHub API 在一次提交中编辑多个文件

javascript - SignalR 不适用于 Chrome 和 Internet Explorer

c# - 通过 C++ 包装器从 java 调用 c# dll 时出错

c# - 在一行中对齐两个段落