【问题标题】:Can I override SqlCommand functions?我可以覆盖 SqlCommand 函数吗?
【发布时间】:2012-07-12 19:47:46
【问题描述】:

我有例如代码

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 函数来执行某种通用异常捕获,而不是这样做吗?

【问题讨论】:

  • 您可以编写一个私有方法来执行某种通用异常捕获并调用它。

标签: vb.net


【解决方案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

【讨论】:

    【解决方案2】:

    不,你不能重写方法,因为你不能从它继承,因为SqlCommandsealed

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

    【讨论】:

      【解决方案3】:

      你也可以使用合成:

      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
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-05
        • 1970-01-01
        相关资源
        最近更新 更多