重做自定义集合以使用任何对象

本文关键字:任何 对象 自定义 集合 重做 | 更新日期: 2023-09-27 18:08:37

我有一些代码,我总是使用我的对象的集合。这段代码在我的一些项目中使用了10次,对象被替换了。

是否有任何方法我可以创建这个函数,可以采取任何对象?我听说过<T>,但我不确定如何在这个中使用它。

public class PageCollection : CollectionBase
    {
        public void Add(Page item)
        {
            InnerList.Add(item);
        }
        public void Remove(int index)
        {
            InnerList.RemoveAt(index);
        }
        public void Remove(Page item)
        {
            InnerList.Remove(item);
        }
        public Page this[int index]
        {
            get
            {
                return (Page)InnerList[index];
            }
            set
            {
                InnerList[index] = value;
            }
        }
    }

重做自定义集合以使用任何对象

只需使用List<T>对象来创建对象的强类型集合。在您的示例中,仅使用

List<Page> listOfPages = new List<Page>()

还检查System.Collections.Generic名称空间的强类型(泛型)集合

最好查看来源:

http://msdn.microsoft.com/en-us/library/512aeb7t.aspx