一些代码来复制问题:
- 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>一样处理.阅读本文: