c# - 接口(interface)如何模拟多重继承?

标签 c# oop inheritance

在寻找在 C# 中使用接口(interface)的原因时,我偶然发现了 MSDN它说:

By using interfaces, you can, for example, include behavior from multiple sources in a class. That capability is important in C# because the language doesn't support multiple inheritance of classes. In addition, you must use an interface if you want to simulate inheritance for structs, because they can't actually inherit from another struct or class.

但是,Interface是如何模拟多重继承的。 如果我们继承了多个接口(interface),仍然需要实现接口(interface)中引用的方法。

任何代码示例将不胜感激!!

最佳答案

这可以使用委托(delegate)来实现。您使用其他类编写一个类,并将方法调用转发(“委托(delegate)”)到它们的实例:

public interface IFoo
{
    void Foo();
}

public interface IBar
{
    void Bar();
}

public class FooService : IFoo
{
    public void Foo()
    {
        Console.WriteLine("Foo");
    }
}

public class BarService : IBar
{
    public void Bar()
    {
        Console.WriteLine("Bar");
    }
}

public class FooBar : IFoo, IBar
{
    private readonly FooService fooService = new FooService();
    private readonly BarService barService = new BarService();

    public void Foo()
    {
        this.fooService.Foo();
    }

    public void Bar()
    {
        this.barService.Bar();
    }
}

关于c# - 接口(interface)如何模拟多重继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27599763/

相关文章:

c# - 如何为 ASP.NET Mvc 缓存数据库中的大量数据

c# - 如何在母版页中设置 View 状态?

javascript - 将值从输入传递到返回对象的构造函数

c# - devexpress gridView.Rows 和单元格?

java - 如何更改包含已更改实例变量的实例变量

c# - 定时任务限制(或者任务持久化是如何实现的)?

c# - 创建泛型类的泛型工厂

cocoa - 将自定义方法添加到子类 NSManagedObject

C++ 不允许我从基类调用公共(public)方法

java - Hibernate 'tableless' 枚举映射?