协变与抗变

4、为什么支持协变的参数只能用于方法的返回值?支持逆变的参数只能用于方法参数?

“TParent不能安全转换成TSub”,是这两个问题的共同原因。
我们定义一个接口IFoo。
 

    interface IFoo<T>
    {
        void Method1(T param);
        T Method2();
    }

我们看一下协变的过程:IFoo<TSub>转换成IFoo<TParent>。

Method1:将TSub替换成TParent,Method1显然存在 TParent到TSub的转换。

Method2:返回值类型从TSub换成了TParent,是类型安全的。

所以支持协变的参数只能用在方法的返回值中。

再看一下逆变的过程:IFoo<TParent>转换成IFoo<TSub>。

Method1:将TParent替换成TSub,Method1存在 TSub到TParent的转换,是类型安全的。

Method2:返回值类型从TParent换成了TSub,是不安全的。

所以支持逆变的参数只能用在方法的参数中。
原文地址:https://www.cnblogs.com/mht91919/p/4538625.html