0

I'm preparing in Monogame a little game engine, where I would want to have something like gameObject composed from DrawableObject And ClickHandler(i.e:

public class GameObject : DrawableObject, ClickHandler

Problem is - C# doesn't support multiple inheritance, I would need to use interface. I've made DrawableObject and ClickHandler abstract classes, so they can have some functionality already implemented.

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
}

Any tips how I could redesign this to be able to implement it? I would like to not have to move whole implementation to every class in which i derive this as interface.

bartexsz
  • 239
  • 1
  • 11

1 Answers1

0

There is a solution on CodeProject: The simulated multiple inheritance pattern for C#

Here is an Example of the most interesting part:

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;
    }
}
Daffi
  • 506
  • 1
  • 7
  • 20
  • 1
    Thanks @Daffi. **moderators**, ignore my flag –  Oct 17 '16 at 07:29
  • Can you check the inheritance in this way? `typeof(Baux) is C` for example – Zorkind Jul 13 '18 at 17:10
  • I think you will find your answer here: https://stackoverflow.com/questions/1218178/c-net-how-can-i-get-typeof-to-work-with-inheritance – Daffi Jul 15 '18 at 19:08