我不知道为什么下面的代码会导致异常?
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;
}
}
最佳答案
您要将真正是temp
的int
直接拆箱到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/