C#列表实现

-2 c# data-structures

我不是很擅长数据结构,但我想尝试在C#List类中使用方法实现添加这是我需要的唯一方法,我无法弄清楚下一步该做什么我只有这段代码

public class myList<T> : List<T>
    {
        public T[] items;
        public int size;

        public myList()
        {

            items = new T[0];
        }
        public myList(int dim)
        {
            items = new T[dim];
        }


        public new void Add(T item)
        {
            items[size++] = item;

        }
    }
Run Code Online (Sandbox Code Playgroud)

我也使用继承到List,因为我不想实现其他东西(接口).当我试图看到我添加到列表(foreach)时我看不到有这些代码的东西我看不到没有.有人可以帮我吗?

Dav*_*vid 9

你继承自List<T>:

public class myList<T> : List<T>
Run Code Online (Sandbox Code Playgroud)

Add(T item)使用您自己的实现覆盖该方法:

public new void Add(T item)
Run Code Online (Sandbox Code Playgroud)

这就是你所要求的全部.因此,当您尝试从对象中读取时,您正在使用所启用的实现List<T>.但是没有任何东西被添加到实现中,因为你的覆盖干预了.就父类的实现而言,没有任何东西被添加到它.

覆盖您需要使用的所有内容,或者不使用该基类.也许你想要实现这个接口:

public class myList<T> : IList<T>
Run Code Online (Sandbox Code Playgroud)

这将迫使您提供该接口所需功能的实现.否则你所拥有的是列表的两个半实现,它们彼此之间没有任何关系.一些功能转到其中一个,其他功能转移到另一个.