What is the .NET object life cycle?

前端 未结 9 2129
一个人的身影
一个人的身影 2020-12-29 09:05

What is the object life cycle for an object in .NET?

From what I understand it is:

  1. Object created - constructor called (if one exists)
  2. Methods
9条回答
  •  清酒与你
    2020-12-29 09:24

    Here is an example class that uses all the information available in the articles provided here. I have already spent hours testing things out, and this is what works best for me.

    /*********************************
     * Author:  Theofanis Pantelides *
     *   Date:  23 Jun 2009          *
     *********************************/
    
    using System;
    using System.IO;
    
    public class MyClass : IDisposable
    {
        String oFile;
        Stream oStream;
    
        public MyClass(String _File)
        {
            oStream = File.OpenRead(oFile = _File);
            // Initialize
        }
    
        ~MyClass()
        {
            this.Dispose();
            // Destruct
        }
    
        public void doSomething()
        {
            // do Whatever it is you are trying to do
        }
    
        #region IDisposable Members
    
        /// 
        /// Dispose all resources used by instance of class
        /// and update Garbage Collector information
        /// 
        public void Dispose()
        {
            if (oStream != null)
            {
                oStream.Dispose(); // Dispose using built in functions
                GC.SuppressFinalize(oStream); // No need for Garbage Collector
            }
    
            oStream = null;  // Nullify it.
        }
    
        #endregion
    }
    

    Usage:

    using(MyClass mc = new MyClass(@"c:\temp\somefile.txt"))
    {
      mc.doSomething();
    }
    

    You can even use the same declaration twice as it does not exist outside the 'using'.

    using(MyClass mc = new MyClass(@"c:\temp\somefile.txt"))
    {
      mc.doSomething();
    }
    
    using(MyClass mc = new MyClass(@"c:\temp\somefile.txt"))
    {
      mc.doSomething();
    }
    

提交回复
热议问题