c# – 为什么不从一个带有where子句的抽象类派生的类转换为它的最低公共类

一些代码来复制问题:
using System;

public abstract class Response { }
public abstract class Request<T> where T : Response { }
public class LoginResponse : Response { }
public class LoginRequest : Request<LoginResponse> { }

public class Program
{
    static void Main(string[] args)
    {
        LoginRequest login = new LoginRequest();


        /* Error: Cannot implicitly convert type 'LoginRequest' to 'Request' */
        Request<Response> castTest = login;


        /* No Error */
        Request<LoginResponse> castTest2 = login;
    }
}

据我所知,LoginRequest类是Request< Response>因为是继承自Request< T>和LoginResponse继承自Response,所以任何人都可以告诉我为什么我得到编译器错误

注意:我也试过一个明确的演员

解决方法

您收到错误,因为请求<响应>和请求< LoginResponse>不协变.

仅仅因为LoginResponse从Response继承并不意味着Request< LoginResponse>可以像Request< Response>一样处理.阅读本文:

MSDN – Covariance and Contravariance in Generics

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...