C# 计时器事件的Main from outside方法中声明的调用实例
这是我第一次使用计时器,我需要调用在Main中声明的类的实例。我的程序是一个魁地奇游戏,这是我的主要任务C# 计时器事件的Main from outside方法中声明的调用实例,c#,events,methods,timer,C#,Events,Methods,Timer,这是我第一次使用计时器,我需要调用在Main中声明的类的实例。我的程序是一个魁地奇游戏,这是我的主要任务 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Timers; using System.Threading.Tasks; namespace QuiddichGame { class Program { pr
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??
}
}
}
您只需要在类级别定义游戏:
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();
}
实际上,不要将
游戏
作为程序
类的字段
相反,请使用具有构造函数的,该构造函数接受对象状态
Game game = //...;
Timer t= new Timer(OnTimedEvent, game, 1000, 1000);
并使用此签名定义您的:
static private void OnTimedEvent(object state)
{
Game game = state as Game;
if(game != null)
{
//...
}
}
@GrantWinney看起来他仍然在用多语言源代码粘贴它。游戏类是我写的一个类,在另一个文件中(它正在工作)。“juego”这个词是我的一个错误,我的代码是西班牙语,但忘了更改它(juego=game)。而且,所有的代码都是我自己写的,可能不是很酷,因为我刚刚接触c。下面的答案有效,我会尽快接受。谢谢非常感谢,这很有效:)。这是一个非常简单的问题!
static private void OnTimedEvent(object state)
{
Game game = state as Game;
if(game != null)
{
//...
}
}