.NET类库中的小知识:弱引用
来源:互联网 发布:淘宝上耐克有正品吗 编辑:程序博客网 时间:2024/06/05 18:07
1、什么是弱引用?
通常情况下,一个实例如果被其他实例引用了,那么他就不会被GC回收,而弱引用的意思是,如果一个实例没有被其他实例引用(真实引用),而仅仅是被弱引用,那么他就会被GC回收。
2、弱引用的用处。
如果建立了一个类“Class人”,他有个属性 “手”。
private Class手 _手;
public Class手 手 {
get { return _手; }
}
public Class手 手 {
get { return _手; }
}
_手 = new Class手();
_手.人 = this;
_手.人 = this;
弱引用就是为了解决这个问题,如果人引用手(真引用),但手弱引用了人,这样释放人的时候,先释放手,而释放手将不再需要先释放人。
3、.NET中实现弱引用
在.NET中,MS在最底层就提供了弱引用功能,在System空间中有个WeakReference类。这里是使用这个类的演示(注意:在Set方法中使用Internal只能在.NET中收到支持,如果你使用.NET 1.x请将set单独提取为SetParent方法)
private WeakReference _parentReference;
/**//// <summary>
/// 返回当前组件的父组件
/// </summary>
public object Parent {
get {
if (_parentReference != null) {
return _parentReference.Target;
}
else {
return null;
}
}
internal set {
if (value == null) {
_parentReference = null;
}
else {
_parentReference = new WeakReference(value);
}
}
}
/**//// <summary>
/// 返回当前组件的父组件
/// </summary>
public object Parent {
get {
if (_parentReference != null) {
return _parentReference.Target;
}
else {
return null;
}
}
internal set {
if (value == null) {
_parentReference = null;
}
else {
_parentReference = new WeakReference(value);
}
}
}
- .NET类库中的小知识:弱引用
- .NET类库中的小知识:弱引用
- NET类库中的小知识:弱引用
- .NET类库中的小知识:弱引用
- asp.net 中的静态变量 (小知识)
- c++引用小知识
- 关于asp.net中的Cookie的一点小知识!
- asp.net中的一些常用的基础小知识
- asp.net小知识
- .net 小知识
- asp.net小知识
- ASP.Net 小知识
- .net/C# 小知识
- MVP模式中的小技巧:软引用与弱引用
- 学习中的小知识
- 开发中的小知识
- swing中的小知识
- iOS中的小知识
- 怎样令到一个Class可以有Serialize能力...
- 关于水晶报表列太多导致设计界面容纳不下的解决方法
- 找书
- 工作的感触
- 如何编写一个自动投票程序
- .NET类库中的小知识:弱引用
- 夏夜漫想
- 集中器与多路复用器
- 编写恶作剧的JAVA程序
- 一个哑巴(雅巴)的诞生!
- VC+SQL Server 的问题
- "我"字的不同点阵字模编码
- 郁闷....
- [原创]半月总结