从Timer Event的外部方法调用Main中声明的实例

本文关键字:Main 声明 实例 调用 方法 Timer Event 外部 | 更新日期: 2023-09-27 17:57:39

这是我第一次使用Timers,我需要调用在Main中声明的类的实例。我的程序是一个Quiddich游戏,这是我的主程序。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Threading.Tasks;
namespace QuiddichGame
{
    class Program
    {
        private static Timer aTimer = new Timer(1000);
        static void Main(string[] args)
        {
            aTimer.Interval = 1000;
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            aTimer.Start();
            Championship champ = new Championship();
            game.GenerateTeams();
            Game game = new Game(champ.teams[0], champ.teams[1]);
            juego.CrearDisplay();
            game.CreateField();
            while (true) { int a = 1; }
        }
        //Actualization
        static private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            //HOW DO I CALL THE "game" INSTANCE IN HERE??
        }
    }
}

从Timer Event的外部方法调用Main中声明的实例

实际上,不要使Game成为Program类的字段。

相反,使用System.Threading.Timer,它有一个接受object state的构造函数。

Game game = //...;
Timer t= new Timer(OnTimedEvent, game, 1000, 1000);

并用这个签名定义您的回调:

static private void OnTimedEvent(object state)
{
    Game game = state as Game;
    if(game != null)
    { 
        //...
    }    
}

您只需要在类级别定义游戏:

class Program
{
    private static Timer aTimer = new Timer(1000);
    //Define your game in the class
    private static Game game;
    static void Main(string[] args)
    {
        aTimer.Interval = 1000;
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.Start();
        Championship champ = new Championship();
        game.GenerateTeams();
        game = new Game(champ.teams[0], champ.teams[1]);
        juego.CrearDisplay();
        game.CreateField();
        while (true) { int a = 1; }
    }
    //Actualization
    static private void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        game.DoSomething();
    }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Threading.Tasks;
namespace QuiddichGame
{
    class Program
    {
        private static Game game
        private static Timer aTimer = new Timer(1000);
        static void Main(string[] args)
        {
            aTimer.Interval = 1000;
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            aTimer.Start();
            Championship champ = new Championship();
            game.GenerateTeams();// this should not be here
            Game game = new Game(champ.teams[0], champ.teams[1]);
            juego.CrearDisplay();
            game.CreateField();
            while (true) { int a = 1; }
        }
        //Actualization
        static private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            //HOW DO I CALL THE "game" INSTANCE IN HERE??
        }
    }
}