C#按类型查询集合/按类型转换元素
示例
interface IFoo { }
class Foo : IFoo { }
class Bar : IFoo { }var item0 = new Foo();
var item1 = new Foo();
var item2 = new Bar();
var item3 = new Bar();
var collection = new IFoo[] { item0, item1, item2, item3 };使用OfType
var foos = collection.OfType<Foo>(); // result: IEnumerable<Foo> with item0 and item1 var bars = collection.OfType<Bar>(); // result: IEnumerable<Bar> item item2 and item3 var foosAndBars = collection.OfType<IFoo>(); // result: IEnumerable<IFoo> with all four items
使用Where
var foos = collection.Where(item => item is Foo); // result: IEnumerable<IFoo> with item0 and item1 var bars = collection.Where(item => item is Bar); // result: IEnumerable<IFoo> with item2 and item3
使用Cast
var bars = collection.Cast<Bar>(); //在第一个项目上抛出InvalidCastException var foos = collection.Cast<Foo>(); //在第三个项目上抛出InvalidCastException var foosAndBars = collection.Cast<IFoo>(); //好
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西