如何用一些进程在动态参数内创建对象?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何用一些进程在动态参数内创建对象?相关的知识,希望对你有一定的参考价值。
当我从MyMenu类创建对象时,我遇到了几个错误
我希望在ctor中
- Id参数将自动增加
- 当我创建对象时,它应该添加到MyMenuList
你介意告诉我正确的方法吗?
My menu class properties
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();
}
}
How I am using it
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我是新手。但是,当我看到负面投票。它让我很伤心。顺便说一下,我说我的语言是如此之低。
答案
你的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;
}
}
以上是关于如何用一些进程在动态参数内创建对象?的主要内容,如果未能解决你的问题,请参考以下文章