[英]C# - Determine which class an object should use on instantiation?
我有 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 類中處理。
我的困境是,在 Entity 類中,如何確定 Entity 將使用哪個 Control 類?
Entity 類當前分配 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());
這種方法稱為依賴注入。 有關更多詳細信息,請參見例如Wikipedia 。
是的,使用泛型:
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
派生,並且可以使用無參數構造函數進行實例化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.