是否有任何可能的方法来访问字段 - 类程序中的str和主函数中的变量num?
class Program
{
string str = "This is a string";
static void Main(string[] args)
{
int num = 100;
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
var timer = new System.Timers.Timer(10000);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
for (int i = 0; i < 20; i++)
{
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId + " " + "current I is " + i.ToString());
Thread.Sleep(1000);
}
Console.ReadLine();
}
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
Debug.WriteLine(str);
Debug.WriteLine(num);
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId + " current is timer");
//throw new NotImplementedException();
}
}
最诚挚的问候,
答案 0 :(得分:1)
该字段只需要static。
static string str = "This is a string";
要访问num
,您需要使用lambda expression。
timer.Elapsed += new ElapsedEventHandler((s, e) =>
{
Debug.WriteLine(str);
Debug.WriteLine(num);
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId + " current is timer");
});
您还可以使用anonymous method。
timer.Elapsed += new ElapsedEventHandler(delegate(object sender, ElapsedEventArgs e)
{
Debug.WriteLine(str);
Debug.WriteLine(num);
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId + " current is timer");
});
还有一个选择。 System.Threading.Timer类允许您传递状态对象。
var timer = new System.Threading.Timer((state) =>
{
Debug.WriteLine(str);
Debug.WriteLine(state);
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId + " current is timer");
}, num, 10000, 10000);
答案 1 :(得分:0)