为什么这个通用铸造失败? [英] Why does this generic cast fail?

查看:145
本文介绍了为什么这个通用铸造失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下继承:

internal abstract class TeraRow{}

internal class xRow : TeraRow {} // xRow is a child of TeraRow

public IEnumerable<TeraRow> Compare(MappedTables which, DateTime selectionStart
        , DateTime selectionEnd, string pwd)
{
    IEnumerable<xRow> result=CompareX();
    return  (IEnumerable<TeraRow>)result; //Invalid Cast Exception? 

}

无法投射类型为System.Collections.Generic的对象.List 1 [xRow]'键入System.Collections.Generic.IEnumerable 1 [TeraRow]

Unable to cast object of type 'System.Collections.Generic.List1[xRow]' to type 'System.Collections.Generic.IEnumerable1[TeraRow]

推荐答案

您需要投射它,因为 IEnumerable< T> ; 在T上不是协变的。您可以这样做:

You need to cast it because IEnumerable<T> is not covariant on T. You can do this:

return result.Cast<TeraRow>();

这篇关于为什么这个通用铸造失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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