抱歉,这是一篇2005年的文章,当时入门。.net不久,此文有误导,正确的是:
.net不使用引用计数器,文中案例的父子互相引用不会不释放,弱引用用于缓存,弱引用事件等。
1、什么是弱引用?
通常情况下,一个实例如果被其他实例引用了,那么他就不会被GC回收,而弱引用的意思是,如果一个实例没有被其他实例引用(真实引用),而仅仅是被弱引用,那么他就会被GC回收。
2、弱引用的用处。
如果建立了一个类“Class人”,他有个属性 “手”。






而在Class手,我希望能够访问“父”,就是人,例如手在收到烫伤后,立即通知“父”:人的子对象“大脑”一个消息“好痛啊”。这个时候,就需要在Class手中定义一个“人”属性,并在Class人初始化时将自己传入。


事实上,这样的做法将造成了“循环引用”的问题,这在COM时代的计数器引用方法的时代将是可怕的问题。因为人引用了手,而手又引用了人,如果试图释放人,将先要释放手,但释放手的前提是要释放人,这就是“循环引用”。
弱引用就是为了解决这个问题,如果人引用手(真引用),但手弱引用了人,这样释放人的时候,先释放手,而释放手将不再需要先释放人。
3、.NET中实现弱引用
在.NET中,MS在最底层就提供了弱引用功能,在System空间中有个WeakReference类。这里是使用这个类的演示(注意:在Set方法中使用Internal只能在.NET中收到支持,如果你使用.NET 1.x请将set单独提取为SetParent方法)






















