C#中的私有继承? [英] Private inheritance in C#?

查看:159
本文介绍了C#中的私有继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的新手,想知道C#中是否存在类似私有继承的东西(比如C ++)?

I'm new to C# and wondered if there is something like private inheritance in C# (like in C++) ?

我的问题如下:
我想实现一个队列(将其命名为SpecialQueue),并进行以下更改:

My problem is as follows: I want to implement a queue (name it SpecialQueue) with the following changes:


  1. 队列中包含的最大项目数可以是存储在其中。

  2. 如果队列已满并且您插入了一个新项目,则一个项目将自动从队列中取出(队列中的第一个项目),新项目将插入到队列末尾。

  3. 队列提供​​的某些方法(如peek())不应暴露给SpecialQueue的用户。

在c ++中我会从队列中私有ihnerit,只暴露我想要的方法,并根据我的意愿改变其他方法。但不幸的是,队列中的所有方法都没有覆盖修饰符,我不知道如何在C#中实现它。

In c++ I would private ihnerit from queue, expose only the methods I want to and change others to my will. But unfortunatley, all methods in queue don't have the "Override" modifier and I don't know how to achieve that in C#.

任何帮助?

问候,
Dan

Regards, Dan

推荐答案

使用构成:包括通常 队列 SpecialQueue 中的字段。私有继承实际上与组合非常相似。

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

参见 http://www.parashift.com/c++-faq-lite/private-inheritance.html#faq-24.3 供讨论。

实施可能是这样的:

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; }
    }
}

如果你需要添加更多功能/接口想要 SpecialQueue 来支持它们。但是我不建议实现 IEnumerable ,因为这将允许 Peek (你想要禁止它)。

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).

这篇关于C#中的私有继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆