Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 接口如何模拟多重继承?_C#_Oop_Inheritance - Fatal编程技术网

C# 接口如何模拟多重继承?

C# 接口如何模拟多重继承?,c#,oop,inheritance,C#,Oop,Inheritance,在寻找在C#中使用接口的原因时,我无意中发现它说: 例如,通过使用接口,您可以包括来自 一个类中有多个源。这种能力在C语言中很重要# 因为该语言不支持类的多重继承。 此外,如果要模拟,必须使用接口 结构的继承,因为它们实际上不能从 另一个结构或类 但是,接口如何模拟多重继承呢。 如果我们继承多个接口,仍然需要实现接口中引用的方法 任何代码示例都将不胜感激 这可以使用委托。您可以使用其他类组成一个类,并将(“委托”)方法调用转发到它们的实例: public interface IFoo {

在寻找在C#中使用接口的原因时,我无意中发现它说:

例如,通过使用接口,您可以包括来自 一个类中有多个源。这种能力在C语言中很重要#
因为该语言不支持类的多重继承。 此外,如果要模拟,必须使用接口 结构的继承,因为它们实际上不能从 另一个结构或类

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


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

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

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

我相信作者将行为视为类的声明行为,而不是实现行为behavior@SergeyBerezovskiy因此,从实际意义上讲,多重继承是不可能的??同样的MSDN多重继承在C#中不受支持。这就是为什么不支持类的多重继承,但支持接口的多重实现。。。