如何将现有项目添加到C#中的集合中#
问题描述:
我正在开发一个通用smartTag面板并从我的项目中派生出基础smartTag。我想在派生的智能标记中添加base smarttag的现有操作项。我想在衍生面板的项目下面添加基础面板的项目。有没有简单的方法来添加基础项目,而不是直接在行动项目下面使用foreach?如何将现有项目添加到C#中的集合中#
public override DesignerActionItemCollection GetSortedActionItems()
{
DesignerActionItemCollection actionItems = new DesignerActionItemCollection();
//adds the new smart tag action items.
actionItems.Add(new DesignerActionHeaderItem("MySmartTag Support"));
actionItems.Add(new DesignerActionPropertyItem("BackColor", "Back Color"));
actionItems.Add(new DesignerActionPropertyItem("ForeColor", "Fore Color"));
//adds the action items from base smart tag.
foreach (DesignerActionItem baseItem in base.GetSortedActionItems())
{
actionItems.Add(baseItem);
}
return actionItems;
}
我在for循环中添加新操作项下的基本操作项,有没有什么办法可以避免循环并尽量减少代码?
答
我找到了答案,插入是最好的选择。
public override DesignerActionItemCollection GetSortedActionItems()
{
DesignerActionItemCollection actionItems = base.GetSortedActionItems();
//inserts the new smart tag action items.
actionItems.Insert(0, new DesignerActionHeaderItem("MySmartTag Support"));
actionItems.Insert(1, new DesignerActionPropertyItem("BackColor", "Back Color"));
actionItems.Insert(2, new DesignerActionPropertyItem("ForeColor", "Fore Color"));
return actionItems;
}
你试过'AddRange'而不是为'Add' –
使用actionItems.AddRange(base.GetSortedActionItems()) – GSP
的AddRange不适用于DesignerActionItemCollection – Amal