.net - 有没有办法绕过 C#.NET 中的单类继承限制?

标签 .net oop inheritance

最近在一次采访中有人问我是否知道一种方法来绕过/规避 .NET 限制,即类只能从单个类继承,而不能从多个类继承。显然我不知道答案,否则我不会在这里问这个问题。缺乏实现多个接口(interface)(这似乎是一个错误的答案)或将类链接到一个继承自另一个继承另一个继承的类,是否还有另一种我不知道的方法来完成此任务?

最佳答案

Short of implementing multiple interfaces (which seemed like a wrong answer) or chaining classes to where one inherits from another that inherits from another, is there another way to accomplish this that I'm not aware of?

不,我怀疑实现多个接口(interface)是正确的答案。

这是相当标准的。假设您有类 FooBar,并且您希望类 FooBarFoo 中“继承” >酒吧。然后创建接口(interface) IFooIBar 并拥有 Foo : IFooBar : IBar。然后你定义 FooBar : IFoo, IBar 和标准实现将是

class FooBar : IFoo, IBar {
    private readonly IFoo foo = new Foo();
    private readonly IBar bar = new Bar();
    // or pass these in as dependencies

    public void Moo() {
        foo.Moo();
    }

    public void Mar() {
         bar.Mar();
    }
}

是的,可能要写很多东西,但并不那么难(VS 或 R# 中有一些工具可以帮助加快一点点)。

关于.net - 有没有办法绕过 C#.NET 中的单类继承限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18044440/

相关文章:

c++ - 在另一个头文件 C++ 中创建一个类的实例

jQuery $.proxy 范围

c# - 如何创建不比较两个单独继承类的抽象基类 IComparable?

inheritance - 你为什么要对整个类(class)进行密封/最终定级?

.net - 无法在 Visual Studio 2012 中加载 SOS.dll 扩展

.net - ListBoxItem 产生 "System.Windows.Data Error: 4"绑定(bind)错误

.net - 应用程序暂停IIS应用程序池.Net 4.5.1

c# - 继承的类可以访问基类吗

.net - WCF 4.0 Rest Service 返回内容类型 text/html

python - super()类继承,菱形继承(钻石问题)