gpt4 book ai didi

c# - 面向对象编程正确使用接口(interface)

转载 作者:行者123 更新时间:2023-11-30 14:57:21 24 4
gpt4 key购买 nike

我正在尝试为一款游戏设计几个类,但我不确定我做得对不对。

我有两个类:ActorBuilding。它们有几个子类:PolicemanFiremanPoliceStationFireStation

我希望能够将所有这些项目放在一个列表中以供以后迭代,因此我添加了一个基类:GameEntity
所以我所拥有的是:

public abstract class GameEntity: 
{
public GameEntity()
{

}
}

public class Actor: GameEntity
{
public int _speed;
public TileSprite _UI;

public Actor()
{

}

public bool CollidesWith(Vector2 pos)
{
//Do stuff here
}

public virtual void OnClick()
{
//Do stuff here
}

public void DoActing()
{

}
}

public class Policeman: Actor
{
public Policeman()
{
_speed = 10;
}

public override void OnClick()
{
//Do stuff
}
}

public class Building: GameEntity
{
public TileSprite _UI;

public Building()
{

}

public bool CollidesWith(Vector2 pos)
{
//Do stuff here
}

public virtual void OnClick()
{
//Do stuff here
}

public void DoBuilding()
{

}
}

public class PoliceStation: Building
{
public PoliceStation()
{

}

public override void OnClick()
{
//Do stuff
}
}

现在,我希望能够做到这一点:

List<GameEntity> Entities = new List<GameEntity>();

Actor a1 = new PoliceMan();
Building b1 = new PoliceStation

Entities.Add(a1);
Entities.Add(b1);

foreach(GameEntity ent in Entities)
{
if (ent.CollidesWith(something))
{
ent.OnClick();

//If Actor then do
ent.DoActing();

//If Building then do
ent.DoBuilding();
}
}

现在,为了做最后一点,我最好实现一个包含 OnClickCollidesWith 的接口(interface),还是可以通过继承来实现?如果是这样,我该怎么做?

干杯。

最佳答案

这只是给你一个想法,我想这就是你所需要的。

 public interface IGameEntity
{
bool CollidesWith();
void OnClick();
void DoActing();
}
public class Actor : IGameEntity { //Interface implemented }
public class Building: IGameEntity { //Interface implemented }
public class Policeman: IGameEntity { //Interface implemented }
public class Fireman: IGameEntity { //Interface implemented }
public class FireStation: IGameEntity { //Interface implemented }

在你的客户端对象中做这样的事情:

List<IGameEntity> entities = new List<IGameEntity>()
{
new Actor(),
new Building(),
new Policeman(),
new Fireman(),
new Fireman()
};
foreach (IGameEntity entity in entities)
{
entity.CollidesWith();
entity.OnClick();
entity.DoActing();
}

关于c# - 面向对象编程正确使用接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20907416/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com