【读】构建可枚举类型(IEnumerator和IEnumerable)
转自:http://www.cnblogs.com/tnspop/archive/2012/03/15/2397666.html
//构建可枚举类型(IEnumerable和IEnumerator),让自定义类型支持类似foreach的枚举
//这个接口告诉调用方对象的子项可以枚举
//public interface IEnumerable
//{
// IEnumerator GetNumerator();
//}
//可以看到,GetEnumerator()方法返回另一个接口System.Collections.IEnumerator的引用。这个接口提供了基础设施,
//调用方法可以用来移动IEnumerable兼容器包含的内部对象:
//这个接口允许调用方获取一个容器的子项
//public interface IEnumerator
//{
// bool MoveNext(); //将光标的内部位置向前移动
// object Current {get;}//获取当前的项(只读属性)
// void Reset();//将光标重置到第一个成员前面
//}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace Garage
{
public class Car
{
private string name;
private double speed;
public Car()
{
name = "null";
speed = 0;
}
public Car(string name, double speed)
{
this.name = name;
this.speed = speed;
}
public string Name
{
get { return name; }
set { name = value; }
}
public double Speed
{
get { return speed; }
}
}
public class Garage:IEnumerable
{
private Car[] carArray;
public Garage()
{
carArray = new Car[4];
carArray[0] = new Car("Rusty", 50);
carArray[1] = new Car("Clunker", 55);
carArray[2] = new Car("Zippy", 30);
carArray[3] = new Car("Fred", 30);
}
/// <summary>
/// 这是一个接口的显示实现
/// </summary>
/// <returns></returns>
IEnumerator IEnumerable.GetEnumerator()
{
//因为System.Array类型已经实现了IEnumerator和IEnumerable的接口,可以简单委托请求到System.Array
//返回数组对象的Enumerator.
return carArray.GetEnumerator();
}
/// <summary>
/// 这是一个接口在对象级别的调用
/// </summary>
/// <returns></returns>
//public IEnumerator GetEnumerator()
//{
// return carArray.GetEnumerator();
//}
}
class Program
{
static void Main(string[] args)
{
Garage carLot = new Garage();
foreach (Car c in carLot)
{
Console.WriteLine("{0} is going {1} MPH", c.Name, c.Speed);
}
//这是在对象级别的引用
//因为GetEnumerator()被定义为公开的,所以,可以在对象级别进行引用
//可以手动和IEnumerator协作
//IEnumerator i = carLot.GetEnumerator();
//i.MoveNext();
//Car myCar = (Car)i.Current;
//Console.WriteLine("{0} is going {1} MPH", myCar.Name, myCar.Speed);
//如果想要在对象级隐藏IEnumerator接口,简单使用显示接口实现就行了
}
}
}
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 从零开始开发一个 MCP Server!
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档