C#泛型,也许是设计思想

本文关键字:设计思想 也许 泛型 | 更新日期: 2023-09-27 18:24:30

我对C#还很陌生,我正在研究它的可能性。

现在我有点困惑,在某种程度上我想使用泛型。。。列出泛型的种类。我想在一个单亲类中创建一个基本的列表功能,并命名我的子类应该包含的类类型。

比方说,我创建了一个类

class ItemList<T> : IList<T> {}

并实现IList接口。在ItemList中将T定义为

public T this[int index] { get; set; }

然后,我想要一个或多个ItemList的子类。例如

class ProductList : ItemList<ProductItem> {}
class CategoryList : ItemList<CategoryItem> {}

现在,当我在ItemList中实现IList接口时,我希望能够访问IndexOf、Add、Insert等具有标识符this或ProductList实例(例如)的方法

ProductItem product = new ProductItem();
ProductList products = new ProductList();
products.Add(product);

三线产品。添加是错误的。

ProductList"不包含"Add"answers"没有接受类型的第一个参数的扩展方法"Add"未能找到ProductList(是否缺少正在使用的指令还是程序集引用?

是我遗漏了一些语法部分,还是这个概念是不可能的?这个想法(目前)只是为了简化以后的使用——如果我有一个ProductList类,它将包含ProductItem,这是合乎逻辑的,为什么我要像一样使用它呢

ProductList<ProductItem> products = new ProductList<ProductItem>(); 

我希望你明白我的意思。

编辑-只是为了在这里明确对象层次结构。。。类ItemList使用方法存根实现IList接口类ProductList继承ItemList类方法存根抛出错误,但它发生在运行时。

项目清单的详细信息

class ItemList<T> : IList<T>
    {
        public T this[int index] { get; set; }
        private List<T> fList = new List<T>();
        int IList<T>.IndexOf(T item)
        {
            return fList.IndexOf(item);
        }
        void ICollection<T>.Add(T item)
        {
            fList.Add(item);
        }
        void IList<T>.Insert(int index, T item)
        {
            fList.Insert(index, item);
        }
        void IList<T>.RemoveAt(int index)
        {
            throw new NotImplementedException();
        }
....
}

C#泛型,也许是设计思想

哦,这很明显。您显式地实现了接口。您可以将产品强制转换为ICollection<产品项>在调用上的方法之前

(products as ICollection<ProductItem>).Add(product);

或者,更好的是,您可以隐式地实现Add方法,如下所示:

public void Add(T item) {
    fList.Add(item);
}

由于要实现接口,因此需要使用自己的代码来实现这些方法。

或者,可以从List而不是IList继承。

这个答案切中要害。当接口方法显式实现时,在基于类类型的变量上看不到它们。您必须将它们强制转换为包含该方法的接口。

您可能已经注意到,在IList<T>接口上实现所有方法需要花费大量的工作。你确定这就是你想要做的吗?只扩展List<T>类会简单得多。或者,更好的是,为什么不将列表作为一个单独的属性公开呢?

public class ItemList<T>
{
    private List<T> _itemList = new List<T>();
    public IList<T> Items {get {return _itemList;}}
    // add other features here.
}

当然,这是假设您有一些其他功能要添加到ItemList中。实际上,完全跳过ItemList<T>类可能更有意义:

public class ProductList : List<ProductItem> {}

简而言之,通常最好避免你试图实现的模式。如果你分享你认为这是必要的原因,我们可能会向你展示其他方法,用更少的工作量来实现同样的结果。