c# 析构函数一定会被调用吗 控制台

  1. 概要

1.1 问:析构函数一定会被调用吗

答:不一定

1.2 试验结果

测试情景

内存回收是否发生

系统结束前后

对象设置为null

是否调用析构感受

1

调用

2

不调

3

是/否

不调

4

前/后

是/否

不调

  1. 代码

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace 析构函数一定会被调用吗
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("");
            MyData myData = new MyData();
            myData.index++;
            
            Console.WriteLine(myData.index);
            myData = null;   // 不置为null 也不会执行析构函数
            GC.Collect();//回收垃圾 ,这里回收会执行析构函数
            Console.ReadKey();
            //GC.Collect();//回收垃圾 ,这里回收 就不会执行析构函数
            // 不调用回收,也不会执行析构函数
        }
    }
    /// <summary>
    /// 测试用的实例
    /// </summary>
    [Serializable]
    class MyData : BindClose
    {
        public int index = 0;
        public MyData()
        {
            load();
        }

        protected override void LoadData(object o)
        {
            MyData myData = (MyData)o;
            this.index = myData.index;
        }
        ~MyData()
        {
            close();
        }
    }
    /// <summary>
    /// 绑定具有备份功能的接口
    /// </summary>
    interface IBindClose
    {
        void close();

    }
    /// <summary>
    /// 具有自己备份功能的类
    /// 关闭的时候备份数据
    /// 构造的时候重新加载备份的数据
    /// </summary>
    [Serializable]
    abstract class BindClose
    {
        public void close()
        {
            lock (this)
            {
                string name = this.GetType().Name;
                using (FileStream fileStream = new FileStream(name, FileMode.OpenOrCreate))
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    binaryFormatter.Serialize(fileStream, this);
                }
            }
            
        }
        public void load()
        {
            lock(this)
            {
                string name = this.GetType().Name;
                using (FileStream fileStream = new FileStream(name, FileMode.OpenOrCreate))
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    if (fileStream.Length > 0)
                    {
                        object o = binaryFormatter.Deserialize(fileStream);
                        LoadData(o);
                    }
                }
            }
            
        }
        abstract protected void LoadData(object o);
    }
}
  1. 运行结果

调用析构函数的时候,数会增加

  1. 附录

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值