c# – 为什么不从一个带有where子句的抽象类派生的类转换为它的
发布时间:2020-12-15 18:31:13 所属栏目:百科 来源:网络整理
导读:一些代码来复制问题: using System;public abstract class Response { }public abstract class RequestT where T : Response { }public class LoginResponse : Response { }public class LoginRequest : RequestLoginResponse { }public class Program{ sta
一些代码来复制问题:
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |