无法将一种类型转换为另一种类型错误 [英] cannot convert one type to another type error

查看:90
本文介绍了无法将一种类型转换为另一种类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接口和一个实现该接口的类,如下所示:

I have a interface and a class which implements that interface as below:

public interface Grid_Result
{
}
public partial class Contract_GetSubsetList_Result : Grid_Result
{
}

然后有一个我调用的方法以返回IEnumerable的Grid_Result项:

I then have a method which I call to return an IEnumerable of Grid_Result items:

public IEnumerable<Grid_Result> GetModelForGrid(string fitlerBy, int filterType, int startIndex, int pageSize){...}

所有这些都可以正常工作,但是当我尝试使用以下方法调用我的方法时:

All this works fine, but when I try to call my method with:

List<Contract_GetSubsetList_Result> results = testcontroller.GetModelForGrid(regNumFilter, filterBy,
            startIndex, pageSize).ToList();

我得到一个错误:

Cannot implicitly convert type 'System.Collections.Generic.List<Test.Grid_Result>' to 'System.Collections.Generic.List<Test.Contract_GetSubsetList_Result>'

我不确定为什么,因为Contract_GetSubsetList_Result确实实现了Grid_Result接口.

I'm not sure why, as Contract_GetSubsetList_Result does implement the Grid_Result interface.

推荐答案

因为 IEnumerable< T> 是协变的,而 List< T> 不是,这意味着您可以t将 List< T> 强制转换为 List< {T的超类}>

Because IEnumerable<T> is covariant but List<T> is not, meaning you can't cast a List<T> to a List<{superclass of T}>

您可以使用 Cast< T> 在创建列表之前投射:

You can use Cast<T> to cast before the list is created:

List<Contract_GetSubsetList_Result> results = 
    testcontroller.GetModelForGrid(regNumFilter, filterBy, startIndex, pageSize)
                  .Cast<Contract_GetSubsetList_Result> // if you KNOW all objects will be of type Contract_GetSubsetList_Result
                  .ToList();

这篇关于无法将一种类型转换为另一种类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆