自定义类中使用foreach()

本文介绍了如何通过实现IEnumerable<T>接口来使自定义的Foreach类支持foreach语句,包括代码实现、枚举器创建及yield关键字的应用。

先上代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ForeachClass
{
    public class Foreach<T> : IEnumerable<T>
    {

        private T[] str;
        private int count=0;

        public Foreach(int n)
        {
            str = new T[n];
        }

        public void Add(T value)
        {
            str[count] = value;
            count++;
        }

        public IEnumerator<T> GetEnumerator()
        {
            foreach (T d in str)
            {
                yield return d;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

    }
}

测试:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ForeachClass
{
    class Program
    {
        static void Main(string[] args)
        {
            Foreach<int> f = new Foreach<int>(10);
            f.Add(2);
            f.Add(4);
            f.Add(56);
            f.Add(77);
            f.Add(34);

            foreach (int a in f)
            {
                Console.WriteLine(a+"  ");
            }
        }
    }
}

您可以通过实现IEnumerable<T>接口来使得Foreach类支持foreach语句。
IEnumerable 只有一个方法:GetEnumerator(),它的工作是返回一个实现了IEnumerator<T>
接口的类。C#语言使用一个新的关键字yield来为创建枚举器(enumerator)提供特殊的帮
助。

 

转载于:https://www.cnblogs.com/zhushangwei/p/3269709.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值