2013-01-23 48 views
0

這是一個後續到以前的問題:C# Static event null from within class靜態函數有不同的靜態類變量?

我有這樣一個類:

public class PlaylistModel { 
    public static event EventHandler PlaylistLoadError; 
    public static int myInt; 

    public static void LoadPlaylist() 
    { 
     try 
     {  
      // do some stuff, simulate exception 
      throw new InvalidOperationException(); 
     } 
     catch(InvalidOperationException ex) 
     { 
      EventHandler handler = PlaylistLoadError; 
      if(handler != null) 
      { 
       PlaylistLoadError(null, null); 
      } 
     } 
    } 
} 

其他地方在節目中,我設置了PlaylistLoadError事件處理程序,就像這樣:

public class MainPage { 

    public MainPage() { 
     PlaylistModel.PlaylistLoadError += MyErrorHandler; 
     PlaylistModel.myInt = 5; 
    } 

    public static void MyErrorHandler(object sender, EventArgs e) 
    { 
     Debug.WriteLine("There was an error"); 
    } 
} 

現在,在LoadPlaylist中,PlaylistLoadError爲null,myInt爲0,儘管將它們設置在別處。之後,當我創建PlaylistModel的實例時,PlaylistLoadError和myInt是正確的值。所以我的問題是 - 做一個類的靜態函數以某種方式訪問​​不同版本的靜態類變量?我檢查了靜態變量的內存地址,它們確實不同,具體取決於我是否處於非靜態函數和靜態函數之內。

+1

編號實際重現問題的郵政編碼。 –

+0

?這是重現問題的代碼... – finkonkanonk

+0

不,我無法運行此操作並重現問題。你需要這個:http://sscce.org/ –

回答

1

靜態變量是靜態的,並且在程序運行時保持不變,除非調用某些內容來改變它。

如果您想了解發生了什麼事我會改變現場:

private static int _myInt; 

,然後添加:

public static int myInt 
{ 
    get { return _myInt; } 
    set { _myInt = value; } 
} 

,然後在上set這樣你就可以添加一個破發點找出它何時被改變。