簡體   English   中英

接口如何模擬多重繼承?

[英]How do interfaces simulate multiple inheritance?

在尋找在C#中使用接口的原因時,我偶然發現了MSDN ,上面寫着:

通過使用接口,您可以例如在一個類中包含來自多個源的行為。 該功能在C#中很重要,因為該語言不支持類的多重繼承。 另外,如果要模擬結構的繼承,則必須使用接口,因為它們實際上不能從另一個結構或類繼承。

但是,Interface如何模擬多重繼承。 如果我們繼承多個接口,仍然需要實現接口中引用的方法。

任何代碼示例將不勝感激!

這使用委派工作。 您可以使用其他類來構成一個類,並將方法調用轉發(“委托”)到它們的實例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM