2012-06-28 63 views
1

我正在寫一種圖像處理程序,允許用戶打開任意數量的圖像。每次用戶打開一個圖像時,程序都必須爲它創建一個對象,該對象由某個類MyClass定義。顯然,當我在「打開圖像」的方法內創建該對象(例如,單擊菜單按鈕文件 - >打開...)時,該對象僅在該方法內部是已知的,並且對於UI的其他方法是無用的。我可以在UI類中創建一個數組,然後將對象分配給MyClass [i]並繼續向上計數,但這不是一個選項,因爲我無法知道用戶想要打開多少圖像。此外,用戶必須能夠再次關閉圖像,這意味着這個索引我將無用。動態創建和刪除對象

有沒有辦法以某種方式有一個對象的集合,我可以動態地添加和刪除對象?對象必須能夠通過說出文件名來識別這個集合中的自己。

我對C#很新,所以請儘量詳細解釋一切。

回答

1

你需要的是像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"]; 
+0

這聽起來不錯,但我可以通過某個關鍵字(如文件名)本地化一個對象嗎? – phil13131

+0

否索引中索引的列表必須是整數。如果您想通過除數字索引之外的其他地址來映射圖像,則必須使用字典。我將在上面擴展我的答案。 –

+0

謝謝,裏德科普塞還建議詞典。 – phil13131

1

您可以將對象存儲在Dictionary<TKey,TValue>中。在這種情況下,您可能需要Dictionary<string, MyClass>

這會讓你查找並保存密鑰,這可能是文件名。

+0

當我嘗試添加詞典<字符串,UI類中的MyClass>我得到errormessage:「非泛型類型'System.IO.Directory'不能用於類型參數」 – phil13131

+0

@ phil13131在你的頂部添加'using System.Collections.Generic;'文件...另外,它是**字典**不是*目錄*( –

+0

它已經包含在內。它可能與MyClass有關嗎?它是否需要具有特定的屬性? – phil13131