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

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

问题描述

我有以下继承:

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]

另外,为什么我要投它呢?

Also why do I need to cast it at all?

推荐答案

您需要转换它,因为的IEnumerable&LT; T&GT; 未在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天全站免登陆