2012-07-12 126 views
0

我的代碼,這將是例如我可以重寫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

回答

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

不,你不能覆蓋方法,因爲你不能從它繼承自SqlCommandsealed

在使用SqlCommand時捕捉(或拋出)異常有什麼問題?

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 

不是說這是最好的選擇,只是它是一個....

相關問題