关于对象dispose的猜想

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_32157579/article/details/101628396
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace Test
{
    public class A : IDisposable
    {
        public A()
        {
            this.BL = new B();
            Console.WriteLine("A对象创建");
        }
        public B BL { get; set; }
        public void Dispose()
        {
            if (this.BL != null)
            {
                this.BL.Dispose();
            }
            Console.WriteLine("A对象Dispose");
        }
    }

    public class B : IDisposable
    {
        public B()
        {
            this.CL = new C();
            Console.WriteLine("B对象创建");
        }
        public C CL { get; set; }

        public void Dispose()
        {
            if (this.CL != null)
            {
                this.CL.Dispose();
            }
            Console.WriteLine("B对象Dispose");
        }
    }

    public class C : IDisposable
    {
        public C()
        {
            Console.WriteLine("C对象创建");
        }
        public C Say()
        {
            Console.WriteLine("C对象Say方法");
            return this;
        }
        public void Dispose()
        {
            Console.WriteLine("C对象Dispose");
        }
    }
    public class Program
    {
        static void Main(string[] args)
        {
            using (A a = new A())
            {
                using (C c = a.BL.CL.Say())
                {
                    Console.WriteLine("using中输出");
                }
            }
        }
    }
}

输出结果
image.png

猜你喜欢

转载自blog.csdn.net/qq_32157579/article/details/101628396