通过


使用 Visual C# 实现自定义集合

本分步文章介绍如何在 Visual C# 中实现自定义集合。 Microsoft .NET Framework 基类库提供集合 System.Collections.ICollection 接口的正式定义。

原始产品版本: Visual C#
原始 KB 数: 307484

在自定义类中实现 ICollection 接口

ICollection 接口继承自 IEnumerable 接口。 该 ICollection 接口定义一个方法和三个 CopyTo 只读属性: IsSynchronizedSyncRootCountICollectionGetEnumeratorIEnumerable接口继承该方法。 自定义集合类应实现 ICollection 接口。

若要实现 ICollection 接口,请执行以下步骤:

  1. 在 Visual C# .NET 中,创建 Windows 应用程序。

  2. 在解决方案资源管理器中,右键单击项目名称,指向“添加”,然后单击“添加类以添加名为 CustomCollection模块。

  3. 将以下示例代码添加到类模块的开头以导入 System.Collection 命名空间:

    using System.Collections;
    
  4. 将模块中的其他任何代码替换为以下示例代码:

    public class CustomCollection : ICollection
    {
        private int[] intArr = {1,5,9};
        private int Ct;
    
        public CustomCollection()
        {
            Ct=3;
        }
    }
    

    为简单起见,该 CustomCollection 类包含一个包含三个整数项和计数变量的数组。

  5. 实现该方法 CopyTo ,该方法采用整数数组和索引作为参数。 此方法将集合中的项复制到从传递的索引处开始的数组。 若要实现此方法,请将以下代码粘贴到公共 CustomCollection 构造函数后面:

    void ICollection.CopyTo(Array myArr, int index)
    {
        foreach (int i in intArr)
        {
            myArr.SetValue(i,index);
            index = index+1;
        }
    }
    
  6. 实现由GetEnumerator接口继承ICollectionIEnumerable的方法。 该方法 GetEnumerator 返回一个 Enumerator 对象,该对象可以循环访问集合。 将以下示例代码粘贴到 CopyTo 方法后面:

    IEnumerator IEnumerable.GetEnumerator()
    {
        return new Enumerator(intArr);
    }
    
  7. 若要实现三个只读属性,请在方法后面 GetEnumerator 粘贴以下代码:

    // The IsSynchronized Boolean property returns True if the
    // collection is designed to be thread safe; otherwise, it returns False.
    bool ICollection.IsSynchronized
    {
        get
        {
            return false;
        }
    }
    
    // The SyncRoot property returns an object, which is used for synchronizing
    // the collection. This returns the instance of the object or returns the
    // SyncRoot of other collections if the collection contains other collections.
    object ICollection.SyncRoot
    {
        get
        {
            return this;
        }
    }
    
    // The Count read-only property returns the number
    // of items in the collection.
    int ICollection.Count
    {
        get
        {
            return Ct;
        }
    }
    

为 GetEnumerator 方法实现枚举器对象

本部分介绍如何创建 Enumerator 可循环访问 CustomCollection的类。

  1. 将以下示例代码粘贴到类模块中的 end class 语句后面:

    public class Enumerator : IEnumerator
    {
        private int[] intArr;
        private int Cursor;
    }
    

    intArr声明私有整数数组,以在调用方法时GetEnumerator保存类的CustomCollection元素。 字段 Cursor 成员在枚举时保留当前位置。

  2. 添加具有参数的 intArr 构造函数,并将本地 intArr 设置为此构造函数。 将以下示例代码粘贴到成员字段的声明之后:

    public Enumerator(int[] intarr)
    {
        this.intArr = intarr;
        Cursor = -1;
    }
    
  3. 实现 ResetMoveNext 方法。 为此,请将以下代码粘贴到构造函数后面:

    void IEnumerator.Reset()
    {
        Cursor = -1;
    }
    bool IEnumerator.MoveNext()
    {
        if (Cursor < intArr.Length)
            Cursor++;
    
        return(!(Cursor == intArr.Length));
    }
    

    ResetCursor 设置为 -1 并将 MoveNext 下一个元素移动到 Cursor 下一个元素。 MoveNext 如果成功,则 返回 True

  4. 实现返回由 Current /a0> 指向的项的 Cursor只读属性。 如果为 Cursor -1,则生成一个 InvalidOperationException. 将以下代码粘贴到 MoveNext 方法后面:

    object IEnumerator.Current
    {
        get
        {
            if((Cursor < 0) || (Cursor == intArr.Length))
                throw new InvalidOperationException();
            return intArr[Cursor];
        }
    }
    

用于循环访问自定义集合

  1. Form1.cs的“ 设计 ”选项卡上,将按钮拖动到窗体。

  2. 双击该按钮,并将以下示例代码添加到 Click 该按钮的事件:

    CustomCollection MyCol = new CustomCollection();
    
    foreach (object MyObj in MyCol)
        MessageBox.Show(MyObj.ToString());
    
  3. 按 F5 运行应用程序,然后单击按钮。

    注意

    消息框显示自定义集合中的项。

WSL 的工作原理是怎样的? 对于每个调用 GetEnumerator 方法来创建 Enumerator 对象,并调用 MoveNext 方法以设置 Cursor 到第一项。 然后,访问当前属性以获取项 MyObj。 这将重复,直到 MoveNext 返回 False