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

Mas*_*low 4 .net generics ienumerable casting

我有以下继承:

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? 

}
Run Code Online (Sandbox Code Playgroud)

无法转换'System.Collections.Generic.List 1[xRow]' to type 'System.Collections.Generic.IEnumerable1 [TeraRow] 类型的对象

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

mqp*_*mqp 17

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

return result.Cast<TeraRow>();
Run Code Online (Sandbox Code Playgroud)