枚举器如何封装数组

问题描述

我有一个起始长度为4的对象数组,每次Add方法到达长度时,长度加倍。该数组实现了 IEnumerable:

 public ObjectArrayCollection()
    {
        this.objectArray = new object[ObjectArrayCapacity];
        Count = 0;
    }

    public int Count { get; protected set; }

    public object this[int index]
    {
        get => this.objectArray[index];
        set => this.objectArray[index] = value;
    }

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

    public ObjectArrayEnumeration GetEnumerator()
    {
        return new ObjectArrayEnumeration(objectArray);
    }

一个实现 IEnumeration 的类:

 public ObjectArrayEnumeration(object[] objectArray)
    {
        this.objectArray = objectArray;
    }
    public object Current
    {
        get
        {
            try
            {
                return objectArray;
            }
            catch (IndexOutOfRangeException)
            {
                throw new InvalidOperationException();
            }
        }
    }
    public bool MoveNext()
    {
        position++;
        return position < objectArray.Length;
    }
    public void Reset()
    {
        position = -1;
    }

“位置

public ObjectArrayEnumeration GetEnumerator()
    {
        return new ObjectArrayEnumeration(objectArray,Count);
    }

但是由于我需要它们,我被告知枚举器应该封装 objectArray。 我试过这个:

public IEnumerator GetEnumerator()
    {
        return objectArray.GetEnumerator();
    }

但这样我就不会枚举这些值。我是 C# 和学习的新手,我的想法已经用完了。 枚举器如何封装objectArray?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)