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

前端之家收集整理的这篇文章主要介绍了c# – 为什么不从一个带有where子句的抽象类派生的类转换为它的最低公共类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
一些代码来复制问题:
  1. using System;
  2.  
  3. public abstract class Response { }
  4. public abstract class Request<T> where T : Response { }
  5. public class LoginResponse : Response { }
  6. public class LoginRequest : Request<LoginResponse> { }
  7.  
  8. public class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. LoginRequest login = new LoginRequest();
  13.  
  14.  
  15. /* Error: Cannot implicitly convert type 'LoginRequest' to 'Request' */
  16. Request<Response> castTest = login;
  17.  
  18.  
  19. /* No Error */
  20. Request<LoginResponse> castTest2 = login;
  21. }
  22. }

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

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

解决方法

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

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

MSDN – Covariance and Contravariance in Generics

猜你在找的C#相关文章