RemoveAt移除(X); 它是否处理元素x?

ele*_*bah 14 c# image list winforms

我有一个Cache来存储每次用户点击下一个图像时最近的两个图像,"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
   }
}
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 20

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

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


Jim*_*hel 13

RemoveAt方法不会调用Dispose图像.在打电话之前,你必须自己处理它RemoveAt.

编辑

如果类型实现IDisposable,那么处理它你写

BackImageList[0].Dispose();
BackImageList.RemoveAt(0);
Run Code Online (Sandbox Code Playgroud)

RemoveAt(0) 基本上:

for (int i = 1; i < BackImageList.Count; ++i)
{
    BackImageList[i-1] = BackImageList[i];
}
BackImageList.Count--;
Run Code Online (Sandbox Code Playgroud)

当然,这一切都是在内部完成的.您无法设置该Count属性.这是通过该RemoveAt方法完成的.

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