繁体   English   中英

为什么这个通用演员会失败?

[英]Why does this generic cast fail?

我有以下继承:

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]' to type 'System.Collections.Generic.IEnumerable对象1[xRow]' to type 'System.Collections.Generic.IEnumerable 1 [TeraRow]

另外,为什么我需要施放它?

你需要抛出它,因为IEnumerable<T>在T上不协变你可以这样做:

return result.Cast<TeraRow>();

请参阅此问题: .NET Casting通用列表

你正在违反逆转。 你需要c#4.0才能工作。 IEnumerable类型无法在2.0到3.5中交换IEnumerable。 关于它的msdn文章是http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx

如果您需要像原始引用一样执行转换列表(在索引处设置项目也设置原始集合中的项目,您可以创建一个实现IList <T>的包装类。(除非我遗漏了某些东西),对于通用解决方案,由于通用约束限制,您需要两个:

public class UpCastList<FromType, ToType> : IList<ToType>
    where FromType : ToType

public class DownCastList<FromType, ToType : IList<ToType>
    where ToType : FromType

另一种可能性是委托转换:

public class CastList<FromType, ToType> : IList<ToType>
{
    public CastList(IList<FromType> source, Func<FromType, ToType> converter) { ... }
}

编辑:如果您只需要一个IEnumerable <T>,那么您可以使用前面提到的Cast <T>扩展方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM