Public Function GetTransformation(ByVal xmldata As String, ByVal Xsltpath As String) As String Dim writer As StringWriter = New StringWriter() Dim strXsl As String = String.Empty Try Dim xslt As New XslCompiledTransform(False) xslt.Load(Path.Combine(Application.StartupPath, Xsltpath)) Dim XmlReader As XPathDocument = New XPathDocument(New StringReader(xmldata)) xslt.Transform(XmlReader, Nothing, writer) strXsl = writer.ToString() writer.Flush() writer.Dispose() Return strXsl Catch generatedExceptionName As Exception Throw End Try End Function
我有上面的函数将xml转换为string。 我可以使用return语句,如下所示
return writer.ToString()
而不是下面给出的函数专家
strXsl = writer.ToString() writer.Flush() writer.Dispose() Return strXsl
最适合最小化内存使用。 在执行函数后在函数中声明的变量和流等等发生了什么?
答案 0 :(得分:3)
是的,你绝对可以使用
return writer.ToString()
StringWriter
IDisposable
实现更好的解决方案是为编写器使用Using
语句,因此总是被释放。摆脱毫无意义的Catch
块,只需将代码更改为:
Public Function GetTransformation(ByVal xmldata As String, ByVal Xsltpath As String) As String
Using writer As StringWriter = New StringWriter()
Dim xslt As New XslCompiledTransform(False)
xslt.Load(Path.Combine(Application.StartupPath, Xsltpath))
Dim XmlReader As XPathDocument = New XPathDocument(New StringReader(xmldata))
xslt.Transform(XmlReader, Nothing, writer)
Return writer.ToString()
End Using
End Function
您应该非常很少明确地调用Dispose
- 您应该总是使用Using
statement代替。