[英]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.