是否有类似 class 的东西可以实现?

Is there something like a class that can be implemented?

我想写一篇
class X (这个)
继承自 A(基础)可以
执行B的方法(?)必须
实现 C 的成员(接口)。

实施A和C没有问题。但是由于 X 不能从多个 class 派生,所以 X 似乎不可能继承 A 和 B 的逻辑。请注意,A 是非常重要的基础 class 而 B 几乎是一个接口,但包含可执行行为.我不希望 B 成为接口的原因是因为每个继承或实现它的 class 的行为都是相同的。

我真的必须将 B 声明为接口并为每个需要 B 行为的 X 实现完全相同的 10 行代码吗?


2个月后
我目前正在学习 C++,以便在 UE4 中使用它 (Unreal Engine 4)。
由于 C++ 比 C# 严格得多,它实际上包含一个 pattern implementation idom 描述这个的术语行为:这些被称为 mixins.

您可以在第 9 页(第二段)阅读有关 C++ mixin here 的一段。

我认为最好的办法是在 A 的构造函数中要求一个 B 的实例,然后根据需要公开或调用 B 的方法:

public class X : A, C
{
    private readonly B _b;

    public X(B b)
    {
        _b = b;
    }
}

如果您查找 Composition over inheritance

,您会发现很多关于这种方法的信息

Do I really must declare B as an interface and implement the exact same 10 lines of code for each X that needs the behaviour of B?

是也不是。您确实需要使 B 成为一个界面。但是公共方法的实现不应该在接口的所有实现中重复。相反,他们应该进入接口 B:

的 class 扩展
public interface B {
    void MethodX();
    void MethodY();
}
public static class ExtensionsB {
    public static void MethodZ(this B b) {
        // Common implementations go here
    }
}

扩展方法提供了一种共享实现 "horizontally" 的方法,而无需让您的 class 继承第二个 class。扩展方法的行为就好像它们是 class:

的常规方法一样
class X : A, B {
    public void MethodX() {...}
    public void MethodY() {...}
}
public static void Main(string[] args) {
    var x = new X();
    x.SomeMethodFromA();
    x.MethodX(); // Calls method from X
    x.MethodY(); // Calls method from X
    x.MethodZ(); // Calls method from ExtensionsB
}