簡體   English   中英

IDisposable對象在使用塊結束之前被放置

[英]IDisposable object disposed before end of using block

我在IDisposable DirectoryEntry周圍有一個using塊,用於創建目錄項,訪問其屬性之一,然后對其進行處理。 但是,目錄條目是在using塊結束之前放置的。

public static PropertyValueCollection GetProperty(
    this Principal principal, string propertyName)
{
    using (var directoryEntry = principal.GetAsDirectoryEntry())
    {
        return directoryEntry.Properties[propertyName];
    }
}

public static DirectoryEntry GetAsDirectoryEntry(
    this Principal principal)
{
    return principal.GetUnderlyingObject() as DirectoryEntry;
}

錯誤return directoryEntry.Properties[propertyName];return directoryEntry.Properties[propertyName]; 行,表示目錄條目已被處理。 我可以刪除using塊,並且代碼可以工作,但是我擔心該對象永遠不會被丟棄。 我多次調用它,因此是否創建了目錄條目的多個實例,並且從不對其進行處置?

您的代碼既不創建DirectoryEntry實例,也不創建Principal.GetUnderlyingObject()方法(這不是工廠方法)。 由於您的代碼無法管理實例的生命周期,因此您的代碼不應處置它。

在這種特定情況下,由Principal.GetUnderlyingObject()返回的實例實際上存儲在Principal實例的狀態中。 處置一次后,在同一Principal實例上對Principal.GetUnderlyingObject()每個后續調用將返回相同的,先前處置的實例。

暫無
暫無

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

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