是什么导致了此代码中的'CA2202: Do not dispose objects multiple times'以及如何重构?



下面的函数用于序列化对象,而不添加XML声明。我刚刚在Visual Studio 2012中打开了包含它的项目,代码分析中出现了"CA2202:不要多次处理对象"警告。

现在,在其他情况下,我已经通过删除[对象]修复了此警告。关闭这是不需要的,但在这种情况下,我看不出需要更改什么,警告的帮助虽然准确,但并不能准确地说明它是如何引起的或如何修复的。

究竟是什么导致了警告的显示,以及如何重构以避免它?

''' <summary>
''' Serialize an object without adding the XML declaration, etc.
''' </summary>
''' <param name="target"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function SerializeElementToText(Of T As New)(target As T) As String
    Dim serializer As New XmlSerializer(GetType(T))
    'Need to serialize without namespaces to keep it clean and tidy
    Dim emptyNS As New XmlSerializerNamespaces({XmlQualifiedName.Empty})
    'Need to remove xml declaration as we will use this as part of a larger xml file
    Dim settings As New XmlWriterSettings()
    settings.OmitXmlDeclaration = True
    settings.NewLineHandling = NewLineHandling.Entitize
    settings.Indent = True
    settings.IndentChars = (ControlChars.Tab)
    Using stream As New StringWriter(), writer As XmlWriter = XmlWriter.Create(stream, settings)
        'Serialize the item to the stream using the namespace supplied
        serializer.Serialize(writer, target, emptyNS)
        'Read the stream and return it as a string
        Return stream.ToString
    End Using 'Warning jumps to this line
End Function

我试过了,但也不起作用:

    Using stream As New StringWriter()
        Using writer As XmlWriter = XmlWriter.Create(stream, settings)
            serializer.Serialize(writer, target, emptyNS)
            Return stream.ToString
        End Using
    End Using 'Warning jumps to this line instead

这是一个错误警告,由XmlWriter处理您传递的流引起。这会使StringWriter处理两次,第一次是由XmlWriter,第二次是由Using语句。

这不是问题,处理。NET框架对象两次不是错误,也不会引起任何问题。如果Dispose()方法实现得不好,它可能会成为一个问题,FxCop不会冒险不告诉你它的情况,因为它在其他方面不够聪明,无法知道Dispose(()方法是否正确。

没有任何方法可以重写代码以避免出现警告。StringWriter实际上并没有任何要处理的内容,所以将其从Using语句中移出是可以的。但这将产生另一个警告,CA2000。最好的做法就是忽略这个警告。如果不想再次查看SuppressMessageAttribute,请使用它。

尝试修改代码,使其具有两个单独的using:

Using stream As New StringWriter()
    Using writer As XmlWriter = XmlWriter.Create(stream, settings)
    End Using
End Using

相关内容

最新更新