我第一次使用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??
}
}
}
答案 0 :(得分:1)
实际上,不要将Game
作为Program
类的字段。
相反,请使用System.Threading.Timer
,其中包含一个带object state
的构造函数。
Game game = //...;
Timer t= new Timer(OnTimedEvent, game, 1000, 1000);
使用此签名定义您的callback:
static private void OnTimedEvent(object state)
{
Game game = state as Game;
if(game != null)
{
//...
}
}
答案 1 :(得分:0)
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??
}
}
}
答案 2 :(得分:0)
你只需要在班级定义游戏:
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();
}