C#泛型 - 为什么需要一个明确的类型从一个具体类型回T? [英] C# generics - why is an explicit cast needed to from a concrete type back to T?

查看:65
本文介绍了C#泛型 - 为什么需要一个明确的类型从一个具体类型回T?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这已经困扰了我一段时间。我有一个小麻烦了解为什么需要在下面的代码显式转换:

This has been bothering me for a while. I'm having a little trouble understanding why explicit casts are needed in the following code:

public static class CastStrangeness
{
    public class A
    {
    }

    public class B
        : A
    {
    }

    public static void Foo<T>(T item)
        where T : A
    {
        // Works.
        A fromTypeParameter = item;

        // Does not compile without an explicit cast.
        T fromConcreteType = (T)fromTypeParameter;

        // Does not compile without an explicit cast.
        Foo<T>((T)fromTypeParameter);
    }

    public static void Bar(A item)
    {
        // Compiles.
        Foo<A>(item);
    }
}



在我看来,T是保证是一个A,所以肯定是编译器可以推断,A的任何实例是保证分配到T?否则,我将无法到A或A B传递到美孚()。所以,我想什么?

It seems to me that T is guaranteed to be an A, so surely the compiler could infer that any instance of A is guaranteed to be assignable to T? Otherwise, I wouldn't be able to pass an A or a B into Foo(). So what am I missing?

PS。我试图寻找关于这个关键字的无尽排列,但每次结果似乎风指的协变和逆变WRT通用接口:)

PS. I've tried searching for endless permutations of keywords on this, but every result seems to wind up referring to covariance and contravariance WRT generic interfaces :)

推荐答案

取的情况:

Foo(new B());

您的第一个任务是确定的:

Your first assignment is ok:

A fromtypeParameter = item;



由于B:A

Since B : A.

不过,此分配是不正常:

But this assignment is not ok:

T fromConcreteType = fromTypeParameter;

由于你很可能已经分配fromTypeParameter为:

Because you could very well have assigned fromTypeParameter as:

fromTypeParameter = new A();



,你显然不能转换为T(即b在这种情况下)。 T比一个更具体的,它可以从A派生所以,你可以走一条路而不是其他,没有一个明确的CAST(可能失败)。

Which you obviously cannot cast to T (which is B in this instance). T is more specific than A, it could be derived from A. So you can go one way but not the other, without an explicit cast (which may fail).

这篇关于C#泛型 - 为什么需要一个明确的类型从一个具体类型回T?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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