是否有任何可能的方式來訪問類程序中的字段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();
}
}
最好的問候,
沒想到用匿名方法做這件事。 – GrayWizardx 2009-12-16 02:42:37
如果你有興趣,你可能想閱讀關閉。 http://en.wikipedia.org/wiki/Closure_%28computer_science%29 – ChaosPandion 2009-12-16 03:01:27