我可以重写SqlCommand函数吗?

问题描述:

我的代码,这将是例如我可以重写SqlCommand函数吗?

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函数来完成某种通用的异常捕获的?

+0

你可以写,做某种通用的异常的私有方法取而代之的是它。 – 2012-07-12 19:51:06

没有,但你可以创建一个通用的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 

不,你不能覆盖方法,因为你不能从它继承自SqlCommandsealed

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

您还可以使用组成:

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 

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