返回IEnumerable <IMyInterface>将无法正常工作 - 必须使用IEnumerable <MyObj>

gol*_*ger 0 .net c#

我想回来IEnumerable<IMyInterface>.我有一个类,MyClass:IMyInterface我从一个函数返回.

IEnumerable<IMyInterface> test() {
    tmpList = new List<MyClass>();
    tmp1 = new MyClass();
    tmp2 = new MyClass();
    tmpList.Add(tmp1);
    tmpList.Add(tmp2);
    return tmpList;
}
Run Code Online (Sandbox Code Playgroud)

编译器不允许,这对我来说似乎很奇怪,因为MyClass:MyInterface.编译器给出了错误'cannot implicitly convert type System.Collections.Generic.IEnumerable<MyClass> to System.Collections.Generic.IEnumerable<IMyInterface. An explicit conversion exists. Are you missing a cast?'

(IEnumerable<IMyInterface>)tmp在运行时没有强制转换异常我无法执行返回.我错过了什么?我希望返回IEnumerable接口应该可以正常工作.

Eri*_*sch 5

你应该做这个:

IEnumerable<IMyInterface> test() {
    tmpList = new List<IMyInterface>();  // this is the important bit
    tmp1 = new MyClass();
    tmp2 = new MyClass();
    tmpList.Add(tmp1);
    tmpList.Add(tmp2);
    return tmpList;
}
Run Code Online (Sandbox Code Playgroud)

或者,你可以这样做:

return tmpList.Cast<IMyInterface>(); // requires using System.Linq in usings
Run Code Online (Sandbox Code Playgroud)