繁体   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