空条件运算符和CA2202:请勿多次放置对象

问题描述 投票:1回答:2

具有以下内容:

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块中的空条件运算符有点奇怪,还是Visual Studio中的分析工具根本不理解它?

编辑:可能相关:Why does Code Analysis flag me when using the null conditional operator with Dispose()?

c# static-analysis try-catch-finally ca2202 null-conditional-operator
2个回答
0
投票

因为您在using块中声明了xw,所以当您退出using块时,将调用XmlTextWriter的IDisposable方法。由于您的字符串编写器仅与XMLWriter一起使用,它也将由垃圾回收器处理(这是一种优化方法,可以避免GC依赖于引用计数来确定对象是否仍在使用中。)

编辑:可以在this MSDN文章中找到更多信息。


0
投票

警告'CA2202'是正确的。

如果创建了'xw',则应在'xw'中将其删除;如果'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();
}
© www.soinside.com 2019 - 2024. All rights reserved.