C#多个抽象类组合设计

时间:2016-10-17 06:29:19

标签: c# object-composition

我正在Monogame中准备一个小游戏引擎,在那里我希望得到类似于DrawableObject和ClickHandler组成的gameObject(即:

public class GameObject : DrawableObject, ClickHandler

问题是 - C#不支持多重继承,我需要使用接口。我已经制作了DrawableObject和ClickHandler抽象类,因此他们可以实现一些功能。

public abstract class ClickHandler
{
    public class NullClick : ClickHandler
    {
        public override void Click(Point mousePos)
        {
            Debug.Print("Clicked on: " + mousePos + ". NullClickHandler assigned");
        }
    }
    private readonly byte _handlerId;

    public static readonly NullClick NullClickHandler = new NullClick();
    private ClickHandler() {}
    public ClickHandler(ref ClickMap clickMap)
    {
        _handlerId = clickMap.registerNewClickHandler(this);
    }

    public abstract void Click(Point mousePos);

    void unregisterHandler(ref ClickMap clickMap)
    {
        clickMap.releaseHandler(_handlerId);
    }
}

class DrawableObject
{
    Texture2D texture;
    public Rectangle position;

    public DrawableObject()
    {
        position = Rectangle.Empty;
    }

    void Load(ref GraphicsDevice graphics)
    {
        using (var stream = TitleContainer.OpenStream("Content/placeholder.jpg"))
        {
            texture = Texture2D.FromStream(graphics, stream);
            position.Width = texture.Width;
            position.Height = texture.Height;
        }
    }
    void Draw(){} //here is going to be some default implementation
}

有关我如何重新设计以便能够实现它的任何提示?我不想将整个实现移动到我将其作为接口派生的每个类。

1 个答案:

答案 0 :(得分:1)

CodeProject上有一个解决方案:The simulated multiple inheritance pattern for C#

以下是最有趣的部分示例:

class Aaux : A
{
    C CPart;

    m1();

    static implicit operator C(Aaux a)
    {
        return a.CPart;
    }
}

class Baux : B
{
    C CPart;

    m2();

    static implicit operator C(Baux b)
    {
        return b.CPart;
    }
}

class C
{
    Aaux APart;
    Baux BPart;

    m1()
    {
        APart.m1();
    }
    m2()
    {
        BPart.m2();
    }

    static implicit operator A(C c)
    {
        return c.APart;
    }
    static implicit operator B(C c)
    {
        return c.BPart;
    }
}