C# 的析构以及垃圾回收实例分析
作者:lqh 时间:2021-12-22 19:03:37
C# 的析构以及垃圾回收实例分析
看书时,自己写的例子代码,了解到几个知识点,记载下来。同时发现自己手写代码的能力比较弱,还是得多写一下。
using System;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
fun();
GC.Collect(); //4、若不显式回收,则控制台不打印回收行。
Console.WriteLine("end!");
}
public static void fun(){ //1、此处必须有static
A a=new A();
a.Dispose();
//GC.Collect(); //3、此处回收无效,因为a还没释放
}
public class A:IDisposable{
/* protected override void Finalize(){ //2、析构实际是重载Finalize,但不能直接写重载。编译器自动重写Finalize,所以代码中,只能用 析构函数。
Console.WriteLine("some one disposed!");
}*/
~A(){
Console.WriteLine("some one Finalize!");
}
public void Dispose(){
Console.WriteLine("some one disposed!");
}
}
}
}
1、该代码的输出为:
Hello World!
some one disposed!
end!
some one Finalize!
这个回收像极了异步调用!
2、IDisposable接口的Dispose方法,目的是“不用户不再使用对象时,要手工调用它”
比如文件打开,数据库访问等。需要及时释放。
明显这个概念和垃圾回收是两个概念。释放后,该对象仍然存在,有待运行环境来回收,见最后一行。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
来源:https://my.oschina.net/u/1540190/blog/734409
标签:C#,析构,垃圾回收
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Spring与Shiro整合及加载权限表达式问题
2023-10-01 09:29:50
![](https://img.aspxhome.com/file/2023/0/79880_0s.jpg)
Java实现synchronized锁同步机制
2022-07-16 20:19:04
![](https://img.aspxhome.com/file/2023/5/100045_0s.jpg)
Android Recyclerview实现多选,单选,全选,反选,批量删除的功能
2021-12-10 21:57:24
![](https://img.aspxhome.com/file/2023/6/96776_0s.jpg)
Java实现常见排序算法的优化
2022-05-20 13:08:37
Android自定义View实现竖直跑马灯效果案例解析
2021-06-25 04:04:30
![](https://img.aspxhome.com/file/2023/7/99797_0s.gif)
java中Integer包装类装箱的一个细节详解
2023-09-24 18:35:32
android studio实现简单的计算器小功能
2022-07-22 17:53:26
![](https://img.aspxhome.com/file/2023/9/98619_0s.jpg)
C#中类与接口的区别个人总结
2023-05-08 17:29:40
javaweb上传下载实例完整版解析(上)
2021-07-31 05:40:23
![](https://img.aspxhome.com/file/2023/4/63114_0s.jpg)
C# 使用相同权限调用 cmd 传入命令的方法
2023-06-01 23:36:45
JAVA中数组从小到大排序的2种方法实例
2021-10-09 09:46:18
java实现微信扫码登录第三方网站功能(原理和代码)
2023-08-04 00:44:11
![](https://img.aspxhome.com/file/2023/3/93233_0s.png)
C# 添加、修改以及删除Excel迷你图表的实现方法
2023-04-06 22:07:27
![](https://img.aspxhome.com/file/2023/6/81046_0s.png)
Spring的事务机制实例代码
2021-09-11 07:46:23
![](https://img.aspxhome.com/file/2023/6/88576_0s.png)
Java日常练习题,每天进步一点点(33)
2023-09-22 05:32:41
SpringCloud分布式链路追踪组件Sleuth配置详解
2023-11-28 23:58:42
![](https://img.aspxhome.com/file/2023/6/60666_0s.png)
一文带你学会规则引擎Drools的应用
2022-04-03 08:40:59
![](https://img.aspxhome.com/file/2023/0/66670_0s.png)
Java异常处理中的各种细节汇总
2023-09-26 02:50:17
![](https://img.aspxhome.com/file/2023/8/79828_0s.jpg)
Java下载远程服务器文件到本地(基于http协议和ssh2协议)
2022-08-29 12:23:18
![](https://img.aspxhome.com/file/2023/2/97952_0s.png)
在springboot中实现个别bean懒加载的操作
2023-11-25 09:44:11
![](https://img.aspxhome.com/file/2023/3/60033_0s.jpg)