且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

处置在C#中的循环中创建的对象

更新时间:2021-12-13 02:53:52

对于处置对象,我们可以调用

For disposing object we can call the Dispose method or wrap the object with a using block.

在您的情况下,您创建BitmapImageImageTextBlockStackPanel.这些类均未实现 IDisposable .因此,您不需要处理这些对象,只需将它们从列表中删除(然后没人会对其进行引用),然后

In your case, you create BitmapImage, Image, TextBlock and StackPanel. None of these classes implement IDisposable. So, you don''t need to dispose the objects, just remove them from the list (and then no one will have a reference to them), and the GC will free them.


就像Shmuel Zang所说的那样,您无需在意在给定的上下文中.您正在创建一些对象并将它们放在列表中.
在完成for循环的当前迭代之后,它们将保留对对象的唯一引用.而且由于该列表应该包含对这些对象的引用,因此处置它们不是一个好主意.
如果过了一段时间,列表将其引用丢弃了,则垃圾收集器将处理未引用的对象.

例如:您不能创建new Image();,因为Image是抽象类.相反,您可以直接
Image img = new Bitmap(myimagesfile.FullName);.
Just as Shmuel Zang said, you don''t need to care about that in the given context. You are creating some objects and put them in a list.
After the current iteration of the for loop is done, the holds the only references to your objects. And since the list is supposed to hold references to the objects, disposing them would not be a good idea.
If, some time later, the list throws its references away, the Garbage Collector will take care of the unreferenced objects.

As for the example: you can''t create a new Image(); because Image is an abstract class. Instead you can directly
Image img = new Bitmap(myimagesfile.FullName);.


在添加新对象之前,请先遍历spList子级,然后逐一处理它们,
然后将新的子代添加到spList.
Before adding new objects iterate through spList children and dispose them one by one ,
and then add new children to spList.