using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 弱引用
{
class Program
{
static void Main(string[] args)
{
Person p = new Person("黑",18);
WeakReference wr = new WeakReference(p); //将p声明为弱引用wr //弱引用类型关键字为WeakReference
p = null;
object o = wr.Target; //这个地方一定要先引用了另外一种方法是不对的
if (o != null)
{
p = o as Person;
Console.WriteLine(p.ToString());
}
//这是另一种方法,这是不对的,因为wr随时可能释放掉,如果判断时没有释放,进入了判断条件一瞬间可能释放wr,这就造成o可能是null
//if (wr.Target != null)
//{
// object o = wr.Target;
//}
Console.ReadKey();
}
}
class Person
{
public Person(string name,int age)
{
this.Name = name;
this.Age = age;
}
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
public override string ToString()
{
return this.Name + this.Age;
}
}
}
C#的弱引用
最新推荐文章于 2024-09-12 15:58:17 发布