gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:35:43 26 4
gpt4 key购买 nike

在寻找在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com