我有下面的函数,用于序列化对象而不添加XML声明。我刚刚打开了包含Visual Studio 2012的项目,而Code Code正在提出“CA2202:不要多次丢弃对象”#39;警告。
现在在其他情况下我通过删除[对象]修复了此警告。不需要关闭但在这种情况下我无法看到需要更改的内容和{{ 3}}虽然准确无法确切地了解它是如何引起的或如何解决它。
究竟是什么导致警告显示,我如何重构以避免它?
''' <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
答案 0 :(得分:12)
这是一个错误警告,由XmlWriter处理您传递的流引起。这使得你的StringWriter被放置两次,首先是XmlWriter,再次是你的Using语句。
这不是问题,两次处理.NET框架对象不是错误,也不会造成任何麻烦。如果Dispose()方法实现不好,可能会出现问题,FxCop没有机会不告诉你它,因为它不够聪明,不知道Dispose()方法是正确的。
没有任何方法可以重写代码以避免警告。 StringWriter实际上没有任何要处理的东西,所以将它移出Using语句是可以的。但这将产生另一个警告,CA2000。最好的办法就是忽略这个警告。如果您不想再次查看它,请使用SuppressMessageAttribute。
答案 1 :(得分:0)
尝试修改代码以使用2个单独的用法:
Using stream As New StringWriter()
Using writer As XmlWriter = XmlWriter.Create(stream, settings)
End Using
End Using