在c#构造函数中使用时会出现溢出异常

时间:2016-07-11 14:24:26

标签: c#-4.0

我有一个这样的课程

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

当我试图在构造函数中进行如下操作时,我得到一个溢出异常错误

 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;

在构造函数中,但我无法初始化它。任何人都可以告诉我,我做错了什么。我认为构造函数用于初始化变量,但我无法将其进行入侵。 谢谢你的帮助。

1 个答案:

答案 0 :(得分: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