![](/img/trans.png)
[英]Is it possible in C# to have interface with fields of another interface but in the implementation use a class that implements an interface?
[英]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.