最近在一次采访中有人问我是否知道一种方法来绕过/规避 .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)是正确的答案。
这是相当标准的。假设您有类 Foo
和 Bar
,并且您希望类 FooBar
从 Foo
和 中“继承” >酒吧
。然后创建接口(interface) IFoo
和 IBar
并拥有 Foo : IFoo
和 Bar : 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/