【发布时间】: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<IAnimal> 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