为什么我不能投INT到T,但可以投的int对象,然后对象为T? [英] Why can't I cast int to T, but can cast int to object and then object to T?

查看:200
本文介绍了为什么我不能投INT到T,但可以投的int对象,然后对象为T?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码不能编译:

public T Get<T>()
{
    T result = default(T);
    if(typeof(T) == typeof(int))
    {    
        int i = 0;
        result = (T)i;
    }

    return result;
}



然而,这段代码编译:

however, this code does compile:

public T Get<T>()
{
    T result = default(T);
    if(typeof(T) == typeof(int))
    {    
        int i = 0;
        result = (T)(object)i;
    }

    return result;
}



中的代码也能正常工作。我不明白为什么编译器可以投一个对象(实际类型可以是任何东西),以T,但不能投一个int(从对象inherets)至T

The code also works fine. I don't understand why the compiler can cast an object (actual type could be anything) to T, but cannot cast an int (which inherets from object) to T.

推荐答案

SLaks 说,编译器知道T是转换为对象,但这只是它的一半。编译器也知道T类型的任何对象从对象派生,因此它需要允许从对象向下转换到T.集合预V2.0需要这一点。不当然t,但能够从对象到向下转换的任何类型。这本来是不可能得到什么的集合为别的不是一个对象。

As SLaks, says the compiler knows that that T is convertible to object but that's only half of it. The compiler also know that any object of type T derives from object, so it needs to allow downcasts from object to T. Collections pre v2.0 needed this. Not to T of course but to be able to downcast from object to any type. It would have been impossible to get anything out of a collection as anything else than an object.

同样谈到T和INT的时候是不正确的。你的代码是当然在运行时这些问题的安全,由于if语句,但编译器无法看到。一般而言(在此情况下,虽然)证明,如果你将永远不会得到一个身体的一些外部条件是否真实的情况下的 NP完全因为我们希望编译在某些时候完成的,它不会去尝试,基本解决了的千年大奖问题

The same is not true when talking about T and int. You code is of course safe from those problems at runtime due to the if statement but the compiler can't see that. In general (not in this case though) proving that you will never get to the body of an if in the case of some external condition being true is NP-complete and since we wish the compile to complete at some point, it's not going to try and basically solve a millenium prize problem

有许多场景中代替T A特定类型不会在非通用代码允许的。
如果你不能写代码作为非通用对于T与特定类型的替代,这不是有效的,不只是在这种情况下,但一般。如果你知道,对方法的所有您的使用情况下,它实际上是有效的,你可以使用限制您泛型方法

There are many scenarios where substituting a specific type for T would not be allowed in non generic code. If you can't write the code as non generic for any substitution of T with a specific type, it's not valid, not just in this case but generally. If you know that for all your use cases of the method it would actually be valid, you can use constraints to your generic method

这篇关于为什么我不能投INT到T,但可以投的int对象,然后对象为T?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆