合并实现相同接口的两个类列表

Max*_*ime 1 c# interface list

在课堂上,我处理一个列表IInterface.

我希望以一种单独的方式处理这两种可能的实现,因此:

public List<IInterface> Process(List<IInterface> InterfaceList)
{
    List<FirstImplementation> FirstList = FirstProcess(InterfaceList.OfType<FirstImplementation>.ToList());

    List<SecondImplementation> SecondList = SecondProcess(InterfaceList.OfType<SecondImplementation>.ToList());

   return new List<IInterface> {
    FirstList,
    SecondList
};

}
Run Code Online (Sandbox Code Playgroud)

我想返回一个List<IInterface>,与输入一样,两者都比预期的要困难

   return new List<IInterface> {
    FirstList,
    SecondList
};
Run Code Online (Sandbox Code Playgroud)

编译但在运行时抛出InvalidCastException,

return new List<IInterface>.AddRange(FirstList).AddRange(SecondList);
Run Code Online (Sandbox Code Playgroud)

甚至不编译......

这样做的正确方法是什么?

dec*_*cPL 8

使用Linq:

return FirstList.Cast<IInterface>().Concat(SecondList.Cast<IInterface>()).ToList();
Run Code Online (Sandbox Code Playgroud)

Cast<>返回一个枚举(mind linq的延迟执行),其中元素强制转换为目标类型,Concat组合两个枚举并将ToList结果转换为列表(并实现linq查询).

正如@Evk亲切地注意到的,当从两种类型到输出类型的隐式转换(在你的情况下,你可以将你的类型转换为它们的公共接口)时,你可以完全跳过转换(尽管在这种情况下你需要显式指定连接类型,如下所示:

return FirstList.Concat<IInterface>(SecondList).ToList();
Run Code Online (Sandbox Code Playgroud)

  • 你根本不需要 Cast,你可以只做 `FirstList.Concat&lt;IInterface&gt;(SecondList).ToList();` (2认同)