我正在开发一个程序,其中每个项目都可以包含一组项目(我正在制作一个菜单,它具有树状结构)
目前我将项目作为列表而不是数组,但我觉得我没有充分利用它来简化代码。我选择了一个列表而不是标准数组,因为接口(.add、.remove 等)很有意义。
我有代码来搜索结构并返回名称的路径(即 Item.subitem.subsubitem.subsubsubitem)。下面是我的代码:
public class Item
{
                                                                //public Item[] subitem; <-- Array of Items
    public List<Item> subitem;                                  // <-- List of Items
    public Color itemColor = Color.FromArgb(50,50,200);
    public Rectangle itemSize = new Rectangle(0,0,64,64);
    public Bitmap itemBitmap = null;
    public string itemName;
    public string LocateItem(string searchName)
    {
        string tItemName = null;
        //if the item name matches the search parameter, send it up)
        if (itemName == searchName)
        {
            return itemName;
        }
        if (subitem != null)
        {
            //spiral down a level
            foreach (Item tSearchItem in subitem)
            {
                tItemName = tSearchItem.LocateItem(searchName);
                if (tItemName != null)
                    break;  //exit for if item was found
            }
        }
        //do name logic (use index numbers)
        //if LocateItem of the subitems returned nothing and the current item is not a match, return null (not found)
        if (tItemName == null && itemName != searchName)
        {
            return null;
        }
        //if it's not the item being searched for and the search item was found, change the string and return it up
        if (tItemName != null && itemName != searchName)
        {
            tItemName.Insert(0, itemName + ".");  //insert the parent name on the left -->  TopItem.SubItem.SubSubItem.SubSubSubItem
            return tItemName;
        }
        //default not found
        return null;
    }
}
我的问题是,是否有更简单的方法来处理列表?关于应该使用列表还是只使用数组,我一直在脑海中反复思考。我有一个列表的唯一原因是我不必在每次添加或删除项目时编写代码来调整数组的大小。