2009-12-16 24 views
0

是否有任何可能的方式來訪問類程序中的字段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(); 
    } 
} 

最好的問候,

回答

1

現場只需要進行static

static string str = "This is a string"; 

要訪問你需要使用一個lambda expressionnum

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); 
+0

沒想到用匿名方法做這件事。 – GrayWizardx 2009-12-16 02:42:37

+0

如果你有興趣,你可能想閱讀關閉。 http://en.wikipedia.org/wiki/Closure_%28computer_science%29 – ChaosPandion 2009-12-16 03:01:27

0

如果您將str更改爲靜態,則應該直接訪問str,因爲它是在類級別實現的。 Num是main的內部數據,因此除非您傳遞對它的引用,否則無法訪問。您可以將它移到main的外部,或者如果它在ElapsedEventArgs中支持,則傳遞它的引用並以此方式檢索它。

+0

剛剛檢查,它看起來像ElapsedEventArgs沒有一個對象來保持狀態。您需要提供全局引用(將num移到類級別)或提供可以使用委託或類似方法訪問的引用指針。 – GrayWizardx 2009-12-16 02:32:50