C# 关于弱引用
创建一个对象,用过之后,存储为弱引用;过一段时间想要再次使用该对象,如果此对象并没有被垃圾回收,则直接使用,此操作被称为“弱引用”
1.main 主函数
static void Main(string[] args)
{
//弱引用
Person p = new Person();
p.Name = "Laurel";
p.Age = 18;
WeakReference wr = new WeakReference(p);//将对象弱引用起来
Console.WriteLine("---------------------");
p = null;
//执行了很多程序之后
Console.WriteLine("=====================");
Console.WriteLine("=====================");
Console.WriteLine("=====================");
Console.WriteLine("=====================");
Console.WriteLine("=====================");
Console.WriteLine("=====================");
object o = wr.Target;//首先引用该对象(避免后续被垃圾回收掉)
if (o != null)//对象不为null,说明没有被垃圾回收掉
{
Person p1 = o as Person;
//可以开始使用Person对象了,该对象还是原来的对象
Console.WriteLine(p1.Name);
Console.WriteLine(p1.Age);
}
Console.WriteLine("======================");
Console.ReadKey();
}
2.Person类
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}