Private inheritance in C#?

只谈情不闲聊 提交于 2019-12-05 03:51:49

Use composition: include a usual Queue as a field in your SpecialQueue. Private inheritance is actually something very similar to composition.

See http://www.parashift.com/c++-faq-lite/private-inheritance.html#faq-24.3 for discussion.


Implementation could be something like that:

public class SpecialQueue<T>
{
    private int capacity;
    private Queue<T> storage;

    public SpecialQueue(int capacity)
    {
        this.capacity = capacity;
        storage = new Queue<T>();
        // if (capacity <= 0) throw something
    }

    public void Push(T value)
    {
        if (storage.Count == capacity)
            storage.Dequeue();
        storage.Enqueue(value);
    }

    public T Pop()
    {
        if (storage.Count == 0)
            throw new SomeException("Queue is empty");
        return storage.Dequeue();
    }

    public int Count
    {
        get { return storage.Count; }
    }
}

You need to add more functions/interfaces if you want SpecialQueue to support them. I would however not recommend to implement IEnumerable, because this would allow Peek (which you want to prohibit).

You could implement the same interfaces as a Queue (or Queue<T>), have a Queue as a backing field and expose those methods that you need to, which will simply wrap the calls to the backing field.

For example (have kept implementation of ICollection in line with Queue<T>)

public class SpecialQueue<T> : IEnumerable<T>, ICollection
{
    private readonly Queue<T> _queue;

    #region Constructors

    public SpecialQueue()
    {
        _queue = new Queue<T>();
    }

    public SpecialQueue(int capacity)
    {
        _queue = new Queue<T>(capacity);
    }

    public SpecialQueue(IEnumerable<T> collection)
    {
        _queue = new Queue<T>(collection);
    }

    #endregion

    #region Methods

    // implement any methods that you want public here...

    #endregion

    #region Interface Implementations

    public IEnumerator<T> GetEnumerator()
    {
        return _queue.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return _queue.GetEnumerator();
    }

    public void CopyTo(Array array, int index)
    {
        ((ICollection) _queue).CopyTo(array, index);
    }

    public int Count
    {
        get { return _queue.Count; }
    }

    public object SyncRoot
    {
        get { return ((ICollection) _queue).SyncRoot; }
    }

    public bool IsSynchronized
    {
        get { return ((ICollection) _queue).IsSynchronized; }
    }

    #endregion
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!