How to delete object?

前端 未结 9 1520
眼角桃花
眼角桃花 2021-02-13 18:39

I need to create a method of class that delete the instance.

public class Car
{
    private string m_Color;

    public string Color
    {
        get { return m         


        
9条回答
  •  没有蜡笔的小新
    2021-02-13 18:43

    I would suggest , to use .Net's IDisposable interface if your are thinking of to release instance after its usage.

    See a sample implementation below.

    public class Car : IDisposable
    {
    
       public void Dispose()
       {  
          Dispose(true);
           // any other managed resource cleanups you can do here
           Gc.SuppressFinalize(this);
       }
       ~Car()      // finalizer
       {
            Dispose(false);
       }
    
       protected virtual void Dispose(bool disposing)
       {
         if (!_disposed)
         {
          if (disposing)
          {
            if (_stream != null) _stream.Dispose(); // say you have to dispose a stream
          }
    
          _stream = null;
        _disposed = true;
        }
    
       }
    }
    

    Now in your code:

    void main()
    {
       using(var car = new Car())
       {
         // do something with car
       } // here dispose will automtically get called. 
    }
    

提交回复
热议问题