在简单的类上实现IDisposable

时间:2015-09-13 09:52:04

标签: vb.net

我想为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

当我第一次写下这些字母" Implements IDisposable"但是,整个代码墙都跳进了课堂。我看了msdn,看看有什么,但那里有更多的代码如何正确地#34;实现IDisposable。

从我记得以前写过简单的IDisposable课程开始,我在上面的课程中所做的就足够了。有什么变化吗?

2 个答案:

答案 0 :(得分:4)

这是“代码墙”,附带一些额外的评论。

' 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

我同意GSeng,这是实现IDisposable的正确方法。

答案 1 :(得分:0)

我不知道这对发布者是否重要,但是当我今天在我的班级添加“ Implements IDisposable”时,创建的代码将GC.SuppressFinalize(Me)行注释掉。

答案中未将其注释掉。如果它应该处于活动状态,则也删除此帖子。如果应该将其注释掉,则可能要修复答案。