是什么导致'CA2202:不要多次丢弃对象'在这段代码中,我该如何重构?

Car*_*ger 5 vb.net code-analysis visual-studio

我有下面的函数,用于序列化对象而不添加XML声明.我刚刚打开了包含Visual Studio 2012的项目,而Code Analysis正在提出'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
Run Code Online (Sandbox Code Playgroud)

我试过这个,但它也不起作用:

    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
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 12

这是一个错误警告,由XmlWriter处理您传递的流引起.这使得你的StringWriter被放置了两次,首先是XmlWriter,再次是你的Using语句.

这不是问题,两次处理.NET框架对象不是错误,也不会造成任何麻烦.这可能是一个问题,如果Dispose()方法是执行不力,FxCop的不采取它的机会不会告诉你,因为这是没有其他足够聪明,知道如果一个Dispose()方法是正确的.

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