C# - 确定对象在实例化时应使用哪个类?



>我有2个类:实体和控件。

实体:

public class Entity
{
public float Rotate {get; private set;}
readonly Control m_Control
public Entity(float rot)
{
Rotate = rot;
m_control = new Control();
}
public void Update(float time)
{
switch (m_control.Rotating())
{
case Control.Rotator.Right:
Rotate += time * 1.5f;
break;
case Control.Rotator.Left:
Rotate -= time * 1.5f;
break;
case Control.Rotator.Still:
break;
default:
break;          
}
}

}

控制:

public class Control
{
private Random rnd = new Random();
private int _randomTurn;
public enum Rotator
{
Still,
Right,
Left
}
public Control()
{
TimerSetup(); // Initialize timer for Entity
}
public Rotator Rotating()
{
switch(_randomTurn)
{
case 1:
return Rotator.Right;
case 2:
return Rotator.Left;
default:
return Rotator.Still;
}
}
private void TimerSetup()
{
DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(GameTickTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 2);
dispatcherTimer.Start();
}

private void GameTickTimer_Tick(object sender, EventArgs e)
{
RandomTurn();
}

private void RandomTurn() 
{
_randomTurn = rnd.Next(1, 4);
}

}

基本上,我想将"Control"类作为基类并创建两个子类:PlayerControl和AIControl。 目前,玩家控件输入和 AI 控件输入都在一个 Control 类中处理。

我的困境是,在实体类中,如何确定实体将使用哪个控件类?

实体类当前分配 Control 类,如下所示:

readonly Control m_Control
public Entity(float rot)
{
Rotate = rot;
m_control = new Control();
}

我在另一个类中实例化多个实体类,如下所示:

public class Environment
{
readonly Entity m_entity;
readonly Entity m_entity2;
public Environment()
{
m_entity = new Entity(90.0f);
m_entity2 = new Entity(180.0f);
}

有没有办法让我确定实体在实例化时将使用哪个 Control 子类?

只需通过构造函数传递Control实例即可。您的Entity类将如下所示:

readonly Control m_Control
public Entity(float rot, Control control)
{
Rotate = rot;
m_control = control;
}

创建Entity变量将如下所示:

m_entity = new Entity(90.0f, new PlayerControl());
m_entity2 = new Entity(180.0f, new AIControl());

这种方法称为依赖关系注入。例如,请参阅维基百科以获取更多详细信息。

是的,使用泛型:

public class Entity<TControl> where TControl : Control, new()
{
public float Rotate {get; private set;}
readonly TControl m_Control;
public Entity(float rot)
{
Rotate = rot;
m_control = new TControl();
}
}
public abstract class Control {}
public class PlayerControl : Control {}
public class AIControl : Control {}
public class Environment
{
readonly Entity<PlayerControl> m_entity;
readonly Entity<AIControl> m_entity2;
public Environment()
{
m_entity = new Entity<PlayerControl>(90.0f);
m_entity2 = new Entity<AIControl>(180.0f);
}
}

约束将确保泛型类型派生自Control,并且可以使用无参数构造函数进行实例化。

最新更新