14

每次用户单击下一个图像时,我都有一个缓存来存储最近的两个图像,“RemoveAt(x)”是否处理 x 图像,或者我想要的是删除的图像不在内存中。被完全删除。

 List<Image> BackimageList = new List<Image>();

 private void BackimageListCache(Image img)
{
  BackimageList.Add(img);
  if (BackimageList.Count > 2) 
   {
    BackimageList.RemoveAt(0); //oldest image has index 0
   }
}
4

2 回答 2

21

.NET 中的集合不“拥有”一个对象。所以他们不能假设该对象没有在其他任何地方使用,因此他们不能处置该对象。所有权规则完全由您自己实施。这确实意味着您还必须确保图像不会显示在 PictureBox 中。

确保图像不再占用任何内存也是不确定的。你不能自己管理内存,这是垃圾收集器的工作。但是,Image 使用相当大量的非托管内存来存储像素数据,当您调用 Dispose() 时,该内存确实会被释放。Image 的托管部分保留在内存中,直到 GC 到达它。它很小。

于 2013-04-24T01:16:33.443 回答
15

RemoveAt方法不会调用Dispose图像。在调用之前,您必须自己处理它RemoveAt

编辑

如果类型 implements IDisposable,那么你写的处置它

BackImageList[0].Dispose();
BackImageList.RemoveAt(0);

RemoveAt(0)本质上是:

for (int i = 1; i < BackImageList.Count; ++i)
{
    BackImageList[i-1] = BackImageList[i];
}
BackImageList.Count--;

当然,这一切都是在内部完成的。你不能设置Count属性。是通过RemoveAt方法完成的。

null调用之前无需将值设置为RemoveAt

于 2013-04-24T01:06:01.160 回答