簡體   English   中英

從抽象類方法訪問具體的類類型是一種好習慣嗎?

[英]Is it good practice to access concrete class type from abstract class method?

方案:我有一個抽象類方法,可以根據具體類構造設置的屬性值來調用不同的數據庫存儲過程。 特定的具體類需要向存儲過程發送一個額外的參數。

問:如果具體類是特定類型,從抽象類方法訪問具體類類型並將附加參數發送到數據庫存儲過程是否是一種好習慣? 下面是代碼段:如果我做錯了,請提出建議。

Public MustInherit Class dbBaseCustomField

  Protected _TableName as string

  Public Sub Save(conn as string, customField as CustomField)
   lSqlCommand.CommandType = CommandType.StoredProcedure
   lSqlCommand.CommandTimeout = ApplicationGlobals.cCommandTimeout       
   lSqlCommand.Parameters.Add("@ParentItemId", SqlDbType.Int).Value = piParentItemId
   lSqlCommand.Parameters.Add("@CFChk" , SqlDbType.Int).Value = customField.Value
   If (Me.GetType() Is GetType(MemberCustomField)) Then
    lSqlCommand.Parameters.Add("@AddSyncTrigger ", SqlDbType.Int).Value =    customField.AddSyncTrigger
   End If

   lSqlConnection.Open()
   lSqlCommand.ExecuteNonQuery()
   lSqlConnection.Close()

  End Sub
End Class

Public Class MemberCustomField
  Inherits dbBaseCustomField

  Sub New()
    _TableName = "MemberCustomField"
  End Sub

End Class

Public Class LocationCustomField
  Inherits dbBaseCustomField

  Sub New()
    _TableName = "LocationCustomField"
  End Sub

End Class

注意:由於使用了更多的c#開發人員,因此我使用了VB代碼並標記了C#,這個問題將涉及很多人。 無論是vb.net還是c#,概念都是相同的

更好的方法是在基類中定義一個受保護的,抽象的,僅獲取屬性,該屬性返回一個布爾值,指示該類是否需要額外的參數。 或者,如果僅在極少數情況下為true,則可以在返回false的基類中提供默認實現。 覆蓋MemberCustomField的getter以返回true。

猜猜您已經知道這是不好的做法。
也許問題是,應該怎么做呢?

如果要添加其他參數,請使用虛擬/抽象方法返回這些參數:

    Public Overridable Function ExtraParameters() as List(Of SqlParameters) 

        // your derived classes can return the extra parameters, if any
        Return New List(Of SqlParameter)
    End 

如果您從基類繼承而忘記設置名稱,該怎么辦?

您可能想要檢查已設置_TableName並引發異常,或將表名稱作為參數添加到save方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM