泛型方法中的InvalidCastException

Chr*_*ris 1 c# generics casting

我有以下来源:

    private T GetValue<T>(object value)
    {
        return (T)value;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Int64 integer = GetValue<Int64>(0);
    }
Run Code Online (Sandbox Code Playgroud)

因此,常量0是Int32,必须在泛型方法GetValue中强制转换为Int64.但这会导致InvalidCastException.

但为什么?

当我使用Int64作为参数时,它工作正常.

    private T GetValue<T>(object value)
    {
        return (T)value;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Int64 zero = 0;
        Int64 integer = GetValue<Int64>(zero);
    }
Run Code Online (Sandbox Code Playgroud)

感谢Jon和Brian.我的最终(简化)解决方案是这样的.

    private T GetValue<T>(object value)
    {
        return (T)Convert.ChangeType(defaultValue, typeof(T));
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Int64 integer = GetValue<Int64>(0);
    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

但为什么?

因为你从拆箱装箱intlong.它失败的方式与没有泛型的失败完全相同:

int original = 0;
object boxed = original;
long unboxed = (long) boxed; // Bang!
Run Code Online (Sandbox Code Playgroud)

取消装箱转换必须使用相同的类型(模数枚举和有符号/无符号).