How to make manual alternative to List<> class

2019-08-13 03:21发布

问题:

I need to make alternative to List<> class where I will have 4 methods... Two for adding int items, one from front, other from behind and two for deleting, one from front and other from behind as well. My class should not inherit anything.

Something like this...

public class MyList
{
    public void AddItemsFront(int pItem)
    {

    }

    public void AddItemsBehind(int pItem)
    {

    }

    public void DeleteItemsFront(int pItem)
    {

    }

    public void DeleteItemsBehind(int pItem)
    {

    }
}

回答1:

You could hold an instance of a List<T> in a field, List<T> has already these methods:

public class MyList<T>
{
    private List<T> _TheList;
    public MyList()
    {
        _TheList = new List<T>();
    }
    public List<T> TheList { get { return _TheList; } set { _TheList = value; } }

    public void AddItemFront(T pItem)
    {
        TheList.Insert(0, pItem);
    }

    public void AddItemBehind(T pItem)
    {
        TheList.Add(pItem);
    }

    public void DeleteItemFront()
    {
        TheList.RemoveAt(0);
    }

    public void DeleteItemBehind()
    {
        TheList.RemoveAt(TheList.Count - 1);
    }
}

Since it's a generic class you could also use it for different types than int.

var myList = new MyList<int>();
myList.AddItemFront(1);


回答2:

Create a class that's got a data member of the correct List<> type, and implement your methods by calling the appropriate methods on the List<> data member. You will want your delete operations to return the object they removed from the list.

This is often referred to as the Adapter pattern. Wikipedia has a page on it.