按接口而不是实现拆分实现公共接口的接口集合
Split collections of interfaces implementing a common interface by interface, not by implementations
假设我有以下三个接口:
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()
有专门为此操作制作的 LINQ 方法 - OfType
。它只保留可分配给指定类型的对象,因此您可以:
List<IDog> dogs => Animals.OfType<IDog>().ToList();
List<ICat> cats => Animals.OfType<ICat>().ToList();
假设我有以下三个接口:
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()
有专门为此操作制作的 LINQ 方法 - OfType
。它只保留可分配给指定类型的对象,因此您可以:
List<IDog> dogs => Animals.OfType<IDog>().ToList();
List<ICat> cats => Animals.OfType<ICat>().ToList();