C# 7.0 - 使用默认实现实现多重继承

C# 7.0 - Achieve multiple inheritance with default implementation

问题是:如何同时提供多重继承(C# 不允许)和默认方法实现(C# < 8.0 中的接口不允许)?

一般情况是当我有第一个抽象层,然后是第二个抽象层生成两个不同的 families/categories,最后是属于上述两个 families/categories 的东西的具体实现。

我写的示例代码如下(但请不要过分关注实现细节,仅将其视为描述性场景):

public abstract class Message
{
    protected Guid _id;
    protected string _body;
    protected Message(string body)
    {
        _body = body;
    }
    public override string ToString()
    {
        return _id + "|" + _body;
    }
}
public abstract class ReceivableMessage : Message
{
    private string _receivedFrom;
    public ReceivableMessage(string body, string receivedFrom)
    : base(body)
    {
        _receivedFrom = receivedFrom;
    }
    public string GenerateReply()
    {
        //do some generation
        return "";
    }
}
public abstract class SendableMessage : Message
{
    private string _sendTo;
    public SendableMessage(string body, string sendTo)
    : base(body)
    {
        _sendTo = sendTo;
    }
    public bool CheckReply(ReceivableMessage reply)
    {
        //do some check
        return true;
    }
}

然后我有几个ReceivableMessageSendableMessage的具体实现;但现在我想添加具体的 类 AckMessageNackMessage...它们应该同时扩展 ReceivableMessageSendableMessage (因为两者都可以接收并且可以已发送)...我该如何实现?
作为附加评论,我考虑了两种可能性但放弃了它们:

  1. 用 3 个接口替换 3 个抽象 类。不行,因为我会丢失公共方法实现 ToStringGenerateReplyCheckReply,我应该在所有具体 类 以及公共字段 [= =20=、_body_receivedFrom_sendTo(即使从技术上讲这可以避免用属性替换它们)。
  2. AckReceivableMessageNackReceivableMessage(继承自ReceivableMessage)以及AckSendableMessageNackSendableMessage(继承自[=12]提供具体实现=]).不行,这在我看来是代码重复。

我使用动态分派创建了多重继承。这是实现大规模定制系统属性的一种过于复杂的方法。您从根本上想要的是能够集成来自多个模块的处理。制造架构允许容器以两种方式无限增长——这些术语来自业务——

  • 垂直:扩展流程(而不是子类化)
  • 横向:添加新进程(而不是通过子类化或继承来实现)

多重继承的另一个问题是它引入了歧义。当两个类都被继承时,不清楚应该调用哪个方法。

    class A
    {
        public void One() { ... }
    }
    class B
    {
        public void One() { ... }
    }

然而,大规模定制等制造架构将过程建模为整个过程 类 而不仅仅是方法,因此命名空间可以防止上述问题。

namespace A
{
    class OneProduct { ... }
    class One : Producer<OneProduct>, IProcess { ... }
}

namespace B
{
    class OneProduct { ... }
    class One : Producer<OneProduct>, IProcess { ... }
}

// example of a hardcoded process
namespace IntegratingProcess
{
    class MyProduct { ... }
    class MyProcess : Producer<OneProduct>, IProcess 
    {
        private A.One Machine1 { get; set; }
        private B.One Machine2 { get; set; }
        void D() { // allocate memory for all machines and product DTO }
        void O() { // binds Machine1 and Machine2 to MyProduct reference properties }
        void M()
        {
            Machine1.M();
            Machine2.M();
        }
    }

}

大规模定制允许您动态 集成处理和更改触发顺序。这当然是上述硬编码形式的替代方案,其中生产过程及其触发顺序是在编译时构建的。我的 R 文章介绍了大规模定制,但我不会放弃它的源代码。

我是 POWER 的开发者,它是一种制造架构和有效运用它的规则。我的文章指导程序员如何使用源代码正确建模协作工作。

http://www.powersemantics.com/power.html