我有下面的函数,它用于在不添加 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