如何在.NET 2.0中创建自定义集合

Ash*_*shu 4 c# generics wcf datagridview

嗨,我想创建自定义集合,我从CollectionBase类派生我的自定义集合类,如下所示:

public class MyCollection : System.Collectio.CollectionBase
{
    MyCollection(){}
    public void Add(MyClass item)
    {
        this.List.Add(item);
    }
}

class MyClass
{
    public string name;
}
Run Code Online (Sandbox Code Playgroud)

我来问几个问题:

  1. 当我在.NET 3.5框架上工作时,这种方法是否正确和新.
  2. 我想从我的Web服务(WCF)中公开这个集合.我该怎么做?
  3. 我必须实现GetEnumerator吗?
  4. 这是否会绑定到DataGridView.

Sam*_*ell 6

派生List<T>是有点无意义的,特别是现在它具有IEnumerable<T>构造函数和扩展方法的可用性.它可以除了可以覆盖无虚方法Equals,GetHashCodeToString.(我想你可以从List<T>你的目标是为列表实现Java的toString()功能中获得.)

如果要创建自己的强类型集合类并且可能在添加/删除项时自定义集合行为,则需要从新的(到.NET 2.0)类型派生,该类型System.Collections.ObjectModel.Collection<T>具有受保护的虚拟方法,包括InsertItem并且RemoveItem您可以覆盖以在那些时间执行操作.请务必阅读文档 - 这是一个非常容易派生的类,但您必须意识到公共/非虚拟和受保护/虚拟方法之间的区别.:)

public class MyCollection : Collection<int>
{
    public MyCollection()
    {
    }

    public MyCollection(IList<int> list)
        : base(list)
    {
    }

    protected override void ClearItems()
    {
        // TODO: validate here if necessary
        bool canClearItems = ...;
        if (!canClearItems)
            throw new InvalidOperationException("The collection cannot be cleared while _____.");

        base.ClearItems();
    }

    protected override void RemoveItem(int index)
    {
        // TODO: validate here if necessary
        bool canRemoveItem = ...;
        if (!canRemoveItem)
            throw new InvalidOperationException("The item cannot be removed while _____.");

        base.RemoveItem(index);
    }
}
Run Code Online (Sandbox Code Playgroud)