I'm working in a Console Application and I want to output the value of an array that exist in the main method inside a timer method. I however have no idea how to send the array values to the timer method as the constructor only takes 4 arguments.
static void Main(string[] args)
{
int[] numbers = new int[7] {1, 2, 3, 4, 5, 6, 7};
Timer t = new Timer(TimerOutput, 8, 0, 2000);
Thread.Sleep(10000);
t.Dispose();
Console.ReadLine();
}
private static void TimerOutput(Object state)
{
Console.WriteLine(""); // Here I want to putput the values of numbers[7] from main
Thread.Sleep(1000);
}
答案 0 :(得分:1)
使数组成为Program
类的静态属性。然后事件处理程序可以访问它:
private static int[] numbers;
static void Main(string[] args)
{
numbers = new int[7] {1, 2, 3, 4, 5, 6, 7};
Timer t = new Timer(TimerOutput, 8, 0, 2000);
Thread.Sleep(10000);
t.Dispose();
Console.ReadLine();
}
private static void TimerOutput(Object state)
{
// numbers is available in this method.
Console.WriteLine("");
Thread.Sleep(1000);
}