如何将forms.timer传递给另一个同时使用的类?

时间:2013-12-05 07:41:21

标签: c# .net forms class timer

我在main中有一个计时器,我希望将其传递给一个名为“Enemy”的类。我真的不确定如何正确地做到这一点。这是我的代码的样子。

我的计时器在主要电话“点击”中称为“mastertmr”。点击“Enemy Spawn”,我希望能够以与我的主计时器相同的增量产生敌人。我将其作为“tmr”传递。

主窗口

public MainWindow()
{
    InitializeComponent();

    character = new Character(Background, Dispatcher, keys, Display, 10);
    character.Place(200, 100);
    creatures = new List<Character>();
    enemies = new List<Enemy>();
    creatures.Add(character);
    Display.Content = character.X;
    random = new Random();

    enemymanager = new EnemyManager(Background, Dispatcher, keys, Display, **mastertmr** , 10);


    mastertmr = new System.Windows.Forms.Timer();
    mastertmr.Interval = this.waitTime;
    mastertmr.Tick += new EventHandler(Click);
    mastertmr.Start();
}

public void Click(object sender, System.EventArgs e)
{
    //EnemyManager enemymanager;

    enemymanager.spawn();
}

EnemyManager Class

class EnemyManager
{

    System.Windows.Forms.Timer tmr;
    protected Dispatcher dispatcher;
    protected Canvas Background;
    protected Label Display;
    protected Int32 waitTime;
    protected Dictionary<String, String> keys;
    public int i;

    public EnemyManager(Canvas Background, Dispatcher dispatcher, Dictionary<String, String> keys, Label Display, System.Windows.Forms.Timer tmr, Int32 waitTime =100)
    {
        this.Background = Background;
        this.dispatcher = dispatcher;
        this.keys = keys;
        this.waitTime = waitTime;
        this.tmr = tmr;
    }

    public void spawn()
    {


        tmr.Tick += new EventHandler(hi);
        tmr.Start();
        Enemy enemy;
        i++;

        if (i % 100 == 0)
        {
            enemy = new Enemy(Background, dispatcher, keys, Display, 10);

            enemy.Place(400, 0);
        }
    }


    public void hi(object sender, System.EventArgs e)
    {
        Display.Content = "Hiiiiiiiiiiiiiiiiiiisdfghdfgh";
    }

}

1 个答案:

答案 0 :(得分:1)

我不完全确定你要做什么,但我会避免将计时器传递给敌人的班级。如果你想在每个tick上同时做多件事,我只会在主类的Tick事件上订阅“hi”方法,例如。

enemymanager = new EnemyManager(Background, Dispatcher, keys, Display, 10);
mastertmr = new System.Windows.Forms.Timer();
mastertmr.Interval = this.waitTime;
mastertmr.Tick += new EventHandler(Click);
mastertmr.Tick += new EventHandler(enemymanager.hi);
mastertmr.Start();