【问题标题】:Split collections of interfaces implementing a common interface by interface, not by implementations按接口而不是按实现拆分实现公共接口的接口集合
【发布时间】:2021-01-18 19:28:28
【问题描述】:

假设我有以下三个接口:

IAnimal
IDog:IAnimal
ICat:IAnimal

还有 3 个类:

Beagle: IDog
BullDog: IDog
Persian: ICat

IAnimal 列表中有 2 只波斯犬、1 只斗牛犬和 5 只比格犬。 如何将List<IAnimal> 拆分为List<IDog>List<ICat>。 这样我就可以拥有

List<IDog> Dogs //with 1 BullDog, and 5 Beagles inside
List<ICat> Cats //with 2 Persians inside?

我想创建两个从List&lt;IAnimal&gt; Animals 获取的只读属性。 即

List<IDog> Dogs => Animals.Where(x => x.GetType() == typeof(BullDog) || x.GetType() == typeof(Beagle)).ToList()

但是,这需要我列出所有实现类。 有没有办法通过使用 where 子句中的接口来做到这一点? 即

List<IDog> Dogs => Animals.Where(x => x.IsIDog).ToList()

【问题讨论】:

  • OfType 与接口一起工作,我认为。

标签: c# linq generics interface


【解决方案1】:

有一个专门为此操作制定的 LINQ 方法 - OfType。它只保留可分配给指定类型的对象,因此您可以这样做:

List<IDog> dogs => Animals.OfType<IDog>().ToList();
List<ICat> cats => Animals.OfType<ICat>().ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    相关资源
    最近更新 更多