当我从MyMenu类
创建对象时,我遇到了几个错误我想在ctor中
你介意告诉我正确的方法吗?
public abstract class MenuProperties
{
public byte Id { get; }
public string MenuName { get; set; }
public bool IsSubMenu { get; set; }
public abstract void AddMenu(MyMenu menu);
public abstract void DeleteMenu(MyMenu menu);
public List<MyMenu> MyMenuList { get; set; }
}
public class MyMenu : MenuProperties
{
public MyMenu()
{
Id++; //it's always 0
MyMenuList.Add(this); // How to fix here, stackoverflow error when I run it
}
public override void AddMenu(MyMenu menu)
{
MyMenuList.Add(menu);
}
public override void DeleteMenu(MyMenu menu)
{
MyMenuList.Remove(menu);
}
public override string ToString()
{
return base.Id.ToString() + " " + MenuName.ToString();
}
}
static void Main(string[] args)
{
MyMenu menu = new MyMenu
{
Id = 0,
IsSubMenu = false,
MenuName = "Default",
};
MyMenu menu1 = new MyMenu
{
Id = 1,
IsSubMenu = false,
MenuName = "Home",
};
MyMenu menu2 = new MyMenu
{
Id = 2,
IsSubMenu = false,
MenuName = "Settings",
};
MyMenu menu3 = new MyMenu
{
Id = 3,
IsSubMenu = true,
MenuName = "Add Menu",
};
MyMenu menu4 = new MyMenu
{
Id = 4,
IsSubMenu = true,
MenuName = "Remove Menu",
};
menu.AddMenu(menu);// I wanna just remove this methods
menu1.AddMenu(menu1);// But When I create object from MyMenu class
menu2.AddMenu(menu2);// I wanna add this object to any list when
menu3.AddMenu(menu3);// its created.
menu4.AddMenu(menu4);// I am thinking, it can be in ctor
//But I am taking error.
Console.ReadLine();
}
我可能会有很多逻辑错误bcs我是新手。但是,当我看到负面投票。它让我很伤心。顺便说一句,我说我的语言是如此之低。
答案 0 :(得分:0)
您的MyMenuList
和计数器应该是MyMenu
类的静态成员。
我不知道你会使用MyMenuList
列表,这样就没有任何意义。每个实例在其列表中只有一个项目;本身。此外,引用抽象类的子类型也没有意义。您应该有一个MenuProperties
而不是MyMenu
的列表。如果我错了,请纠正我。
public abstract class MenuProperties
{
private static byte LastId = 0;
public static List<MenuProperties> MyMenuList { get; } = new List<MenuProperties>();
public byte Id { get; }
public string MenuName { get; set; }
public bool IsSubMenu { get; set; }
protected MenuProperties()
{
Id = LastId++;
}
public abstract void AddMenu(MenuProperties menu);
public abstract void DeleteMenu(MenuProperties menu);
}
public class MyMenu : MenuProperties
{
public MyMenu()
{
//This was not a Stack overflow, the MyMenuList was null; you didn't initialise it.
MyMenuList.Add(this);
}
public override void AddMenu(MenuProperties menu)
{
MyMenuList.Add(menu);
}
public override void DeleteMenu(MenuProperties menu)
{
MyMenuList.Remove(menu);
}
public override string ToString()
{
return Id.ToString() + " " + MenuName;
}
}