就像风筝的线,无论飞多远,拉一拉就回来了
如果创建对象很消耗资源,且我们想要避免多次创建同一个对象。 通常在大文件,大字典使用
class Program
{
static void Main(string[] args)
{ //弱引用
Person p = new Person();
p.Name = "名字";//此时p.Name= "名字"
WeakReference wk = new WeakReference(p);
p = null;//此时p为null
//为null后 cg可回收 但是使用弱引用后,可以随时调回来 且值保持不变
if (wk.IsAlive)
{
object o = wk.Target;
if (o != null)
p = o as Person;//Person p1 = o as Person;
//此时p1.Name //p.Name= "名字"
}
}
}
public class Person
{
public string Name { get; set; }
}