簡體   English   中英

另一個類的C#接口實現

[英]C# Interface implementation on another class

我正在嘗試了解一些接口實現細節,需要一些基本的幫助。 鑒於下一個代碼:

public interface IGameObject
{
    Vector3 GetSomePosition();
}

public interface IPlayer : IGameObject
{
    void Die();
}

public class Player : GameObject, IPlayer
{
    void Die() { }
}

我可以在其他類而不是Player類中實現IGameObject接口並使用其他類的實現嗎? 例如,一些名為“GameObjectImplementation”的特殊類,它實現了IGameObject接口。 由於我不能從兩個班級繼承,我該怎么做呢?

- - - - - - - - - - - - - - -編輯 - - - - - - - - - - -------

我現在發現的最佳解決方案是制作基類。

public abstract class PlayerBase : GameObject, IGameObject
{
    public Vector3 GetSomePosition()
    {
        return this.transform.Position;
    }
}

public class Player : PlayerBase, IPlayer
{
    void Die() { }
}

還有其他建議嗎? 像注射或某種顯式實現方式? 或者這是最好的方法嗎?

如果你的意思是這樣的話:

public class GameObjectImplementation: IGameObject
{
    public Vector3 GetSomePosition(){
       return null;
    }
}

public class Player : GameObjectImplementation, IPlayer
{
    public void Die() { }
}

那么是的,你可以。 所述Player類只從繼承GameObjectImplementation和實現IPlayer (直接地)和IGameObject經由的基類。

還要注意,實現方法必須可以從類外部訪問(例如public),因為inteface定義了一個契約,只有外部可訪問的東西才能實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM