2012-06-28 45 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