2016-10-17 95 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