5

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

现在在其他情况下,我已通过删除不需要的 [object].Close 来修复此警告,但在这种情况下,我看不到需要更改的内容,并且在准确时对警告的帮助并不完全正确关于它是如何引起的或如何修复它的信息。

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

''' <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
4

2 回答 2

12

这是一个错误警告,由 XmlWriter 处理您传递的流引起。这使您的 StringWriter 被处理了两次,首先是 XmlWriter ,然后是您的 Using 语句。

这不是问题,两次处理 .NET 框架对象不是错误,也不会造成任何问题。如果 Dispose() 方法实施不当,可能会出现问题,FxCop 不会冒险不告诉您,因为它不够聪明,无法知道 Dispose() 方法是否正确。

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

于 2013-02-05T11:55:58.597 回答
0

尝试修改代码以具有 2 个单独的用途:

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

    End Using
End Using
于 2013-02-05T11:49:20.973 回答