各アイテムがアイテムの配列を保持できるプログラムに取り組んでいます(ツリーのような構造のメニューを作成しています)
現在、配列ではなくリストとしてアイテムを持っていますが、コードを単純化するためにそれを最大限に活用しているとは思えません。インターフェイス(.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;
}
}
私の質問は、リストでこれを行う簡単な方法があるかどうかです。リストを使うべきか、配列だけを使うべきかについて、頭の中で行ったり来たりしてきました。リストがある唯一の理由は、アイテムを追加または削除するたびに配列のサイズを変更するコードを作成する必要がないようにするためです。