簡體   English   中英

我如何處置屬於另一類的屬性的類?

[英]how do i dispose of a class that is a property of another class?

在DC是Service class屬性的情況下,我該如何處置DC?

 class Service()

  {

     public DataContext DC= new DataContext();

     public void SomeMethod()
       {   
          DC is used here.

       }

     public void SomeOtherMethod()
       {
          DC is also used here.
       }

  }

如果您的“服務”類維護對非托管資源的引用,則應實現IDisposable。 這告訴類的客戶,他們需要在“服務”的實例上調用Dispose()。 您可以在類的Dispose()方法中的“ DC”上調用Dispose()。

class Service : IDisposable
{
    public DataContext DC= new DataContext();

    public void Dispose( )
    {
        DC.Dispose( );
    }
}

順便說一句,我會避免在C#中創建公共字段,在公共字段中屬性是常見的習慣用法。

使您的服務ID可用,並在Dispose方法中處理DataContext。 這是一種常見的模式。

您可以在托管類上實現IDisposable ,並在Dispose()方法中處置托管的DC。 然后使用“ using”使用托管類。

using(Service service = new Service())
{
    // do something with "service" here
}

您的Service類應注意處理DataContext。

使用標准的Dispose模式

實施IDisposable: MSDN:實施處置方法

public void Dispose() 
{
    Dispose(true);

    // Use SupressFinalize in case a subclass
    // of this type implements a finalizer.
    GC.SuppressFinalize(this);      
}

protected virtual void Dispose(bool disposing)
{
    // If you need thread safety, use a lock around these 
    // operations, as well as in your methods that use the resource.
    if (!_disposed)
    {
        if (disposing) {
            if (DC != null)
                DC.Dispose();
        }

        // Indicate that the instance has been disposed.
        DC = null;
        _disposed = true;   
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM