---
title: "IEnumerable"
author: "Perrin Yong"
author_profile: https://www.pystone.net/profile/
published_by: "Perrin Yong"
canonical: https://www.pystone.net/notes/csharp-ienumerable/
type: note
content_role: unspecified
visibility: public
id_stability: rename-stable
source_path: "10-计算机、信息技术与工程/02-编程语言与运行时/.NET与CSharp/IEnumerable.md"
content_hash: 0700a2dc6ce194eb85ea857bee2ca822d90e2c298ecc7e5cda9d08012d8bd3aa
knowledge_version: 224c990773de.5fa8af6e39fa
site_commit: 224c990773de166d23a886306577dd90379529ce
notes_commit: 5fa8af6e39fa3891d1b9b4832bfa6c4e0ecaaf0a
---
# IEnumerable

> 创建时间：2020/5/18 13:20

enumerable 可数的，可枚举的
在使用Linq查询数据时经常以IEnumerable来作为数据查询返回对象
使用foreach进行遍历时需要该对象实现IEnumerable接口
定义了一个GetEnumerator()方法
依靠MoveNext和Current来达到Foreach的遍历

定义一个集合FruitShop类，它是一个关于Fruit对象的集合
流程:
第一次遇到foreach里的fruitShop对象时就会去执行FruitShop中的GetEnumerator方法
接着每次执行in关键字就会去执行MoveNext方法
每次取数据则是调用Current属性

```csharp
class MyClass&lt;T, U&gt;
    where T : class
    where U : struct
{ }

```

IEnumerable还有4个扩展方法

  * Cast()

  * OfType()
非泛型集合比如ArrayList，它只实现了IEnumerable接口而没有实现IEnumerable接口，因此无法使用标准查询运算。
但是标准查询运算如此的方便，.NET肯定不会允许这样的不完美发生，于是为IEnumerable提供了2个扩展方法进行强制转换。
OfType比Cast更加强大，它除了进行强制转换外还可以实现类型的过滤，遇到无法强制转换的数据将不会转换
进行转换时OfType是首选

```csharp
class MyClass&lt;T, U&gt;
    where T : class
    where U : struct
{ }

```
