gpt4 book ai didi

vb.net - 在简单类上实现 IDisposable

转载 作者:行者123 更新时间:2023-12-02 09:31:37 25 4
gpt4 key购买 nike

我想为我的 MySql 包装器创建一个辅助类。这个想法是封装 mysql 命令构造和执行的方法有一个可选的 MySqlConnection 作为参数。如果传递了一个特定的连接,它会使用它,如果没有,它会创建一个并在完成后将其处理掉。为了节省每个方法的 4 行,我可以在 using block 中使用此类并将可选参数作为构造参数传递。无论如何,这是类(class):

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 以查看是什么,但那里有更多关于如何“正确”实现 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

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

关于vb.net - 在简单类上实现 IDisposable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32548395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com