2016-07-11 37 views
0

我有這樣越來越溢出異常,而在C#構造函數intiliazing

public class Menu 
    { 
     public int MenuID { get; set; } 
     public string MenuName { get; set; } 
     public string LinkAddress { get; set; } 
     public Menu[] menu; 
} 

一類,而我試圖在構造函數中intilize如下我得到一個溢出異常錯誤

public Menu() { 
      Menu[] menu = { 
           new Menu { MenuID = 1, MenuName = "Home", LinkAddress = "home/index" } 
           , new Menu { MenuID = 2, MenuName = "Gallery", LinkAddress = "Gallery/index" } 
           , new Menu { MenuID = 3, MenuName = "Academics", LinkAddress = "Academics/index" } 
           , new Menu { MenuID = 4, MenuName = "Blog", LinkAddress = "Blog/index" } 
           , new Menu { MenuID = 5, MenuName = "Login", LinkAddress = "Login/index" } 
           , new Menu { MenuID = 6, MenuName = "UserLogin", LinkAddress = "UserLogin/index" } 
           , new Menu { MenuID = 7, MenuName = "ForgotPassword", LinkAddress = "ForgotPassword/index" } 
          }; 
     } 

我也試圖初始化myvariable

public Menu[] menu; 

在構造函數,但我無法intialize我噸。任何人都可以告訴我究竟我做錯了什麼。我認爲構造函數用於初始化變量,但我無法使用它。 感謝您的幫助。

+0

StackOverflowException!= OverflowException。您的默認構造函數創建具有默認構造函數的菜單項。它使用默認構造函數創建菜單項。它使用默認構造函數創建菜單項。它使用默認構造函數創建菜單項。它使用默認構造函數創建菜單項。它用默認的構造函數創建菜單項.... Kaboom!考慮你需要*兩個*類,一個Menu和一個MenuItem類。 –

回答

1

您聲明當類內的類的陣列製成的循環引用:

public Menu[] menu;//<-- declaring inside Menu class produces circular refernce 

從而溢出異常

使用方法來代替,例如:

public void InitMenu() 
     { 
      this.menu = new Menu[]{ 
           new Menu { MenuID = 1, MenuName = "Home", LinkAddress = "home/index" } 
           , new Menu { MenuID = 2, MenuName = "Gallery", LinkAddress = "Gallery/index" } 
           , new Menu { MenuID = 3, MenuName = "Academics", LinkAddress = "Academics/index" } 
           , new Menu { MenuID = 4, MenuName = "Blog", LinkAddress = "Blog/index" } 
           , new Menu { MenuID = 5, MenuName = "Login", LinkAddress = "Login/index" } 
           , new Menu { MenuID = 6, MenuName = "UserLogin", LinkAddress = "UserLogin/index" } 
           , new Menu { MenuID = 7, MenuName = "ForgotPassword", LinkAddress = "ForgotPassword/index" } 
          }; 
     } 

和消耗爲:

Menu m = new Menu(); 
      m.InitMenu(); 
      m.menu=..;//<--acces your array 
+0

以及我想intilize公共菜單[]菜單中的變量,我怎麼能做到這一點 –

+0

在消耗它 – apomene

+0

類聲明它是有沒有辦法在那裏我的intilize變量,而我創建菜單類的對象...謝謝 –