你需要的是像List這樣的動態數據結構。
您可以使用通用(即列表)或非通用(即列表)版本。使用列表,您可以動態添加或插入項目,確定其索引並刪除項目,只要你喜歡。
當您使用列表操作時,列表大小會動態增大/縮小。
假設你的圖像被表示爲Image類型的對象,那麼你可以使用像這樣的列表:
// instantiation of an empty list
List<Image> list = new List<Image>();
// create ten images and add them to the list (append at the end of the list at each iteration)
for (int i = 0; i <= 9; i++) {
Image img = new Image();
list.Add(img);
}
// remove every second image from the list starting at the beginning
for (int i = 0; i <= 9; i += 2) {
list.RemoveAt(i);
}
// insert a new image at the first position in the list
Image img1 = new Image();
list.Insert(0, img1);
// insert a new image at the first position in the list
IMage img2 = new Image();
list.Insert(0, img2);
替代方法通過使用字典:
Dictionary<string, Image> dict = new Dictionary<string, Image>();
for (int i = 0; i <= 9; i++) {
Image img = new Image();
// suppose img.Name is an unique identifier then it is used as the images keys
// in this dictionary. You create a direct unique mapping between the images name
// and the image itself.
dict.Add(img.Name, img);
}
// that's how you would use the unique image identifier to refer to an image
Image img1 = dict["Image1"];
Image img2 = dict["Image2"];
Image img3 = dict["Image3"];
這聽起來不錯,但我可以通過某個關鍵字(如文件名)本地化一個對象嗎? – phil13131
否索引中索引的列表必須是整數。如果您想通過除數字索引之外的其他地址來映射圖像,則必須使用字典。我將在上面擴展我的答案。 –
謝謝,裏德科普塞還建議詞典。 – phil13131