自定义集合


可以通过实现 IEnumerable<T>IEnumerable 接口定义集合。 有关其他信息,请参见 枚举集合如何:使用 foreach 访问集合类(C# 编程指南)

虽然您可以定义自定义集合,但通常最好使用包括在 .NET Framework(本主题前面的集合类型中有所介绍)中的集合。

下面的示例定义名为 AllColors 的客户集合类。 该选件类实现了 IEnumerable 接口,需执行 GetEnumerator 方法。

GetEnumerator 方法返回 ColorEnumerator 类的一个实例。 ColorEnumerator 实现 IEnumerator 接口,这需要首先实现 Current 属性、MoveNext 方法和 Reset 方法。


private void ListColors() {

        var colors = new AllColors();
        foreach(Color theColor in colors){
            Console.WriteLine(theColor.name+" ");
        }
        Console.ReadKey();
    }
    public class AllColors : System.Collections.IEnumerable {
        Color[] _colors = {new Color(){name = "red"},new Color(){name = "blue"},new Color(){name = "green"}} ;

        public System.Collections.IEnumerator GetEnumerator() {
            return new ColorEnumerator(_colors);
        }
    }
    private class ColorEnumerator : System.Collections.IEnumerator {
        private Color[] _colors;
        private int _position = -1;
        public ColorEnumerator(Color[] colors) {
            _colors = colors;
        }
        Object System.Collections.IEnumerator.Current {
            get { return _colors[_position];}
        }
        bool System.Collections.IEnumerator.MoveNext() {
            _position++;
            return (_position <_colors.Length);
        }
        void System.Collections.IEnumerator.Reset() {
            _position = -1;
        }

    }
    public class Color {
        public string name { get; set; }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值