C#:多个 class 个实例都在做同样的事情

C#: Multiple class instances all doing the same thing

我有 3 个不同的 classes:实体、控制和环境

在实体 class 中,我有一个控制变量:

readonly Control m_Control

在我的实体 class 的构造函数中,我正在实例化控件 class。实体 class 中有一个更新方法,它检查控件 class:

中枚举的状态
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;          
            }
     }



}

对照class:

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);
 }


}


Environment class 是我实例化每个实体的地方。所以我会有 2 个 Entity.

实例
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);
}


 public void Update(float time)
        {
            m_entity.Update(time);

            m_entity2.Update(time);
        }
}

我的问题是,当我实例化多个实体时,这些实体中的每一个都做完全相同的事情。

例如,控件class具有旋转功能,但每个实例化的实体在完全相同的时间以完全相同的方式移动。

对我来说最好的方法是什么,以便每个实例化的实体独立行动?

您面临的问题是很难看到的。

问题在于 Random class 的实例化方式。随机生成器以种子值开始,该种子值决定了该生成器返回的所有数字。因此,具有相同种子值的随机生成器的 2 个实例将生成相同的数字序列。现在,如果您在创建随机生成器时不提供种子值,它将根据系统时钟自行创建种子值。但是,如果您紧接着创建 2 个随机生成器,系统时钟将不会改变,它们将收到相同的种子,因此产生相同的序列。

因此,确保您不会同时创建多个 Random 实例始终很重要。

如果您像这样更改 Control class 中的 rnd 属性:

private static Random rnd = new Random();

应该可以。 static 确保此 属性 由 Control class 的所有实例共享(因此只创建一个 Random 实例)。

希望这对您有所帮助,祝您项目顺利!