我可以覆盖SqlCommand函数吗?

时间:2012-07-12 19:47:47

标签: vb.net

我有代码,例如

Dim cmd As New SqlClient.SqlCommand(commandString, databaseString) 
Dim result As Integer

Try
    result = cmd.ExecuteScalar()
Catch e as Exception
    'catch exception code
End Try

我可以覆盖ExecuteScalar函数来执行某种通用异常捕获而不是这样做吗?

3 个答案:

答案 0 :(得分:1)

不,但你可以创建一个通用的DoExecuteScalar辅助函数,它接受一个SQL字符串和连接字符串:

Public Function DoExecuteScalar(commandString as String, databaseString as String) as Object
    Dim cmd as New SqlClient.SqlCommand(commandString, databaseString)
    Dim result as Integer
    Try
        result = cmd.ExecuteScalar()
    Catch e As Exception
        Return 0
    End Try
    Return result
End Function

答案 1 :(得分:1)

不,你不能覆盖方法,因为SqlCommandsealed,你无法继承它。

在您使用SqlCommand时捕获(或抛出)异常有什么问题?

答案 2 :(得分:1)

您也可以使用合成:

Public Class SqlCommandManager
Private _sqlCommand As System.Data.SqlClient.SqlCommand
Public Sub New(command As System.Data.SqlClient.SqlCommand)

    If command Is Nothing Then
        Throw New ArgumentNullException("command")
    End If

    _sqlCommand = command
End Sub
Private ReadOnly Property Command As System.Data.SqlClient.SqlCommand
    Get
        Return _sqlCommand
    End Get
End Property
Public Function ExecuteScalar() As Object
    Dim result As Object

    Try
        result = Command.ExecuteScalar()
    Catch e As Exception
        'catch exception code
    End Try

    Return result
End Function
End Class

不是说这是最好的选择,只是它是一个....