我想为MySql包装器创建一个辅助类。这个想法是封装mysql命令构造和执行的方法有一个可选的MySqlConnection作为参数。如果通过了特定的连接,它将使用该连接,否则将创建一个连接并在完成后将其处置。为了在每种方法上节省4行,我可以在using块中使用此类,并将可选参数作为构造参数传递。无论如何,这是下课:
Public Class DynaConnection
Implements IDisposable
Public Dynamic As Boolean
Public Connection As MySqlConnection
Public Sub New(Connection As MySqlConnection)
If Connection Is Nothing Then
Dynamic = True
Me.Connection = Connect()
Else
Dynamic = False
End If
End Sub
Public Shared Widening Operator CType(ByVal Connection As DynaConnection) As MySqlConnection
Return Connection.Connection
End Operator
Public Sub Dispose() Implements IDisposable.Dispose
If Dynamic Then
Connection.Close()
Connection.Dispose()
End If
GC.SuppressFinalize(Me)
End Sub
End Class
Run Code Online (Sandbox Code Playgroud)
但是,当我第一次写字母“ Implements IDisposable”时,整个类的代码都跳了进去。我看了msdn看看有什么问题,但是那边还有一堆甚至更多的关于如何“正确地”实现IDisposable的代码。
从我之前编写简单的IDisposable类的过程中所记得的东西,我在上面的类中所做的事情就足够了。有什么改变吗?
这就是带有一些附加注释的“代码墙”。
' IDisposable
Protected Overridable Sub Dispose(disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
' TODO: dispose managed state (managed objects).
'If your class holds references to other .NET objects
'that themselves implement IDisposable then you should implement IDisposable
'and call their Dispose method in yours
End If
' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
'If you're holding any OS resources, e.g. file or image handles,
'then you should release them. That will be a rare thing for most people and can be pretty much ignored
' TODO: set large fields to null.
'If any of your fields may refer to objects that occupy
'a large amount of memory then those fields should be set to Nothing
End If
Me.disposedValue = True
End Sub
' TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources.
'Protected Overrides Sub Finalize()
' ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
' Dispose(False)
' MyBase.Finalize()
'End Sub
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
Run Code Online (Sandbox Code Playgroud)
我同意GSeng,这是实现IDisposable的正确方法。
| 归档时间: |
|
| 查看次数: |
5340 次 |
| 最近记录: |