动态创建和擦除对象



我正在编写一种图像处理程序,允许用户打开任意数量的图像。每次用户打开图像时,程序都必须为其创建一个对象,该对象由某个类MyClass定义。显然,当我在"打开图像"的方法中创建此对象时(例如,单击菜单按钮文件 -> 打开...),该对象仅在此方法中是已知的,并且对 UI 的其他方法毫无用处。我可以在 UI 类中创建一个数组,然后将对象分配给 MyClass[i] 并继续计算 i,但这不是一个选项,因为我无法知道用户想要打开多少图像。此外,用户必须能够再次关闭图像,这意味着此索引 i 将毫无用处。

有没有办法以某种方式拥有一个对象集合,我可以动态添加和删除对象?对象必须能够通过文件名来标识此集合中的自己。

我对 C# 很陌生,所以请尝试尽可能详细地解释所有内容。

你需要的是一个动态的数据结构,比如一个列表。

您可以使用通用(即列表)

或非通用(即列表)版本。使用列表,您可以动态添加或插入项目,确定其索引并根据需要删除项目。

列表

的大小会在您使用列表操作时动态增长/缩小。

假设您的图像表示为 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"];
您可以将

对象存储在Dictionary<TKey,TValue>中。 在这种情况下,您可能需要Dictionary<string, MyClass> .

这将允许您根据(可能是文件名)查找和保留项目。

最新更新