vb.net – 在此代码中导致“CA2202:多次不处置对象”的原因是什
发布时间:2020-12-17 00:01:55 所属栏目:大数据 来源:网络整理
导读:我有下面的函数,用于序列化对象而不添加 XML声明.我刚刚打开了包含Visual Studio 2012的项目,而Code Analysis正在提出’CA2202:不要多次丢弃对象’警告. 现在在其他情况下,我通过删除[对象]来修复此警告.不需要关闭.但在这种情况下,我无法看到需要更改的内
我有下面的函数,用于序列化对象而不添加
XML声明.我刚刚打开了包含Visual Studio 2012的项目,而Code Analysis正在提出’CA2202:不要多次丢弃对象’警告.
现在在其他情况下,我通过删除[对象]来修复此警告.不需要关闭.但在这种情况下,我无法看到需要更改的内容,而help for the warning在准确的情况下并不能完全提供信息.它是如何造成的或如何解决它. 究竟是什么导致警告显示,我如何重构以避免它? ''' <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,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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |