如何删除一个类的实例? [英] How to delete an instance of a class?

查看:120
本文介绍了如何删除一个类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有这个项目,创建一个类的多个实例,并列出它们。

So, I have this project that creates multiple instances of a class, and list them.

在某些时候,不需要实例化类了。我怎么能刷新吗?

At some point, the instanced class is not needed anymore. How can I flush it ?

到目前为止,它不会发生,即使类无关了(如果那是一个静态类中,程序会关闭),但它仍然在我的名单,其公共变量仍然可用...

So far, it doesn't happen, even when the class has nothing to do anymore (if it had been a single static class, the program would have shut down), it's still in my list, and its public variables are still available ...

推荐答案

可以有你的情况下,引发事件(OnInactivated,说的)。该列表类应该添加一个处理此类事件时,该项目被添加到列表(子类或封装列表,并覆盖Add方法)。当事件触发时,对象会从列表中的列表中删除。假设该对象未在任何其他列表引用(这也可能是听),则垃圾收集器可以自由地处理的对象。

You can have your instances raise an event (OnInactivated, say). The list class should add a handler for such events when the item is added to the list (subclass or encapsulate a list and override the Add method). When the event fires, the object will be removed from the list by the list. Assuming the object is not referenced in any other lists (which might also be listening), then the garbage collector is free to deal with the object.

在这种方式中, 。对象并不需要跟踪的所有引用的本身,并知道如何告知引用持有者释放参考

In this way, the object does not need to keep track of all references to itself, and know how to inform the reference holder to release the reference.

下面是一个可运行的例子:的 http://www.coderun.com/ide/?w=Hw83i0wAQkugUif5Oj2lmw

Here's a runnable example: http://www.coderun.com/ide/?w=Hw83i0wAQkugUif5Oj2lmw

这篇关于如何删除一个类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆