一些代码来复制问题:
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>一样处理.阅读本文:
原文地址:https://www.jb51.cc/csharp/98758.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。