簡體   English   中英

空條件運算符和 CA2202:不要多次釋放對象

[英]null-conditional operator and CA2202: Do not dispose objects multiple times

具備以下條件:

StringWriter sw = null;
try
{
    sw = new StringWriter();
    using (var xw = new XmlTextWriter(sw))
    {
        doc.WriteTo(xw);
        return sw.ToString();
    }
}
finally 
{
    sw?.Dispose();
}

在 Visual Studio 2015 中觸發CA2202 (不要多次處理對象)警告。

但是如果將fianlly塊更改為:

finally 
{
    if (sw != null)
    {
        sw.Dispose();
    }
}

finally塊中的 null 條件運算符有些奇怪,還是 Visual Studio 中的分析工具根本無法理解它?

編輯:可能相關: 為什么代碼分析在將 null 條件運算符與 Dispose() 一起使用時標記我?

因為您在 using 塊中聲明了 xw,所以當您退出 using 塊時,將調用 XmlTextWriter 的 IDisposable 方法。 由於您的字符串編寫器僅與 XMLWriter 一起使用,因此它也將由垃圾收集器處理(這是一種優化,可以使 GC 不必依賴引用計數來確定對象是否仍在使用中)。

編輯:可以在這篇MSDN 文章中找到更多信息。

警告“CA2202”是正確的。

如果創建了“xw”,則應在“xw”中刪除“sw”,如果“xw”失敗,則應手動刪除。

所以你在創建'xw'之后需要'sw = null'。

StringWriter sw = null;
try
{
    sw = new StringWriter();
    using (var xw = new XmlTextWriter(sw))
    {
        sw = null; //need to set null
        doc.WriteTo(xw);
        return sw.ToString();
    }
}
finally
{
    sw?.Dispose();
}

暫無
暫無

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

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