弱引用

1. 弱引用:当这个对象没有被变量引用的时候,可以被垃圾回收,然后过了一段时间,你可以判断一下,它是否被垃圾回收,如果没有被垃圾回收,那么你就可以再次使用这个对象,否则,就再创建一个对象。

2. 示例代码:

Person per=new Person();

WeakReference wr=new WeakReference(per);

Console.WriteLine("-----per---------");

per = null;

Console.WriteLine("=================");

Console.WriteLine("=================");

Console.WriteLine("=================");

Console.WriteLine("=================");

Console.WriteLine("=================");

//获取原来的值,先引用起来,再判空。因为当你先判空,后引用,在引用之前可能会被垃圾回收。

object o = wr.Target;

if (o != null)

{

Person pe = o as Person;

}

原文地址:https://www.cnblogs.com/taidou/p/4698809.html