2016-10-17 62 views
0

我在Monogame准备一个小游戏引擎,在这里我想有像游戏对象从DrawableObject而clickHandler事件组成(即:C#多抽象类成分设计

public class GameObject : DrawableObject, ClickHandler 

问题是 - C#没有按” T公司的支持多重继承,我需要使用的界面。我做了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

有在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; 
    } 
} 
+1

由于@Daffi。 **版主**,忽略我的标志 – MickyD