C# 枚举器 手动实现枚举器 可枚举集合 枚举器操作 迭代器

本文介绍了如何在C#中手动实现枚举器,以便于通过foreach语句遍历自定义类。当类未实现`IEnumerable`接口时,编译器会报错。通过实现`IEnumerable`接口和`IEnumerator`接口,我们可以为类提供枚举功能。示例中展示了如何为一个未实现枚举接口的Student类添加枚举器,使得可以使用foreach进行遍历。
摘要由CSDN通过智能技术生成

在C#语言中提供 foreach 查询操作,foreach 大大的简化了要编写的代码,但是foreach 只能用来遍历一个可枚举的集合(enumable),可枚举的集合就是实现了System.Collections.IEnumerable接口的一个集合。

 

但是foreach 返回的是可枚举对象的一个只读集合,不可以通过foreach 来修改可枚举对象。

 

简单的一个例子:

 int[] number_array = new int[] { 1,2,3,4,5,6};

 foreach (int k in number_array)
 {
     Console.WriteLine(k);
 }


int 类型,继承了IEnumerable<T> 接口,所有可以用foreach 来遍历。如果我们自己写的一个类,没有实现IEnumerable<T> 接口,用foreach 就不能进行迭代了,编译器会报错。

 

例如:

自己写的一个类:

 class Student: IComparable<Student>
    {
        public Student()
        {
            // nothing
        }

        private int age;

        public int Age
        {
            get { return this.age;}
            set { this.age = value; }
        }

        public int CompareTo(Student other)
        {
            //throw new NotImplementedException();
            if (this.age == other.age)
            {
                return 0;
            }
            else if (this.age < other.age)
            {
                return -1;
            }
            else
            {
                return 1;
            }
        }
    }


 

这个类实现了 IComparable<T> 接口,但是没有实现 IEnumerable<T> 接口,不能用foreach 遍历。

下面的代码对这个没有实现 IEnumerable<T> 接口的类进行foreach 遍历结果发生编译错误。

 

 //Student[] student=new Student[5];
 //student.test();
 //foreach (Student t in student)
 //{
                
 //}


下面我们将自己手动的给上面那个简单的类实现枚举器,通过foreach来遍历这个类。

 

在 IEnumerable接口中,包括一个GetEnumerator的方法:

IEn
  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值