我有两个对象:
public class DPMenu
{
private String menuDescription;
private List<DPMenuItem> menuItems = new List<DPMenuItem>(4); // Initialize list with 4 items
public DPMenu(String menuHeader)
{
menuDescription = menuHeader;
}
public String Description
{
get { return menuDescription; }
set { menuDescription = value; }
}
public List<DPMenuItem> MenuItems
{
get { return menuItems; }
}
}
和
public class DPMenuItem
{
private String itemDescription;
private String itemActionLink;
public String Description
{
get { return itemDescription; }
set { itemDescription = value; }
}
public String Link
{
get { return itemActionLink; }
set { itemActionLink = value; }
}
}
我可以一次创建填充内部列表的对象DPMenu吗? 例如
List<DPMenu> mainMenu = new List<DPMenu>();
DPMenu menuHeader;
List<DPMenuItem> menuItems = new List<DPMenuItem>() {
new DPMenuItem { Description = "A", Link = "A" },
new DPMenuItem { Description = "B", Link = "B" }
};
menuHeader = new DPMenu("HD").MenuItems.AddRange(menuItems);
但它不起作用...... 谢谢!
答案 0 :(得分:1)
为什么不保持简单并只创建另一个重载的构造函数?
public DPMenu(String menuHeader, List<DPMenuItem> itemList)
{
menuDescription = menuHeader;
menuItems = itemList;
}
完成后,只需让您的代码执行以下操作即可。不确定你要做什么,但希望这会有所帮助。
List<DPMenuItem> menuItems = new List<DPMenuItem>() {
new DPMenuItem { Description = "A", Link = "A" },
new DPMenuItem { Description = "B", Link = "B" }
};
menuHeader = new DPMenu("HD", menuItems);