[英]How do you create a generic method in a class?
我真的想遵循DRY原則。 我有一個看起來像這樣的子?
Private Sub DoSupplyModel
OutputLine("ITEM SUMMARIES")
Dim ItemSumms As New SupplyModel.ItemSummaries(_currentSupplyModel, _excelRows)
ItemSumms.FillRows()
OutputLine("")
OutputLine("NUMBERED INVENTORIES")
Dim numInvs As New SupplyModel.NumberedInventories(_currentSupplyModel, _excelRows)
numInvs.FillRows()
OutputLine("")
End Sub
我想使用泛型將這些方法折疊成一個方法。 對於記錄,ItemSummaries和NumberedInventories都是從相同的基類DataBuilderBase派生的。
我無法弄清楚允許我在方法中執行ItemSumms.FillRows和numInvs.FillRows的語法。
FillRows在基類中聲明為Public Overridable Sub FillRows
。
提前致謝。
編輯
這是我的最終結果
Private Sub DoSupplyModels()
DoSupplyModelType("ITEM SUMMARIES",New DataBlocks(_currentSupplyModel,_excelRows)
DoSupplyModelType("DATA BLOCKS",New DataBlocks(_currentSupplyModel,_excelRows)
End Sub
Private Sub DoSupplyModelType(ByVal outputDescription As String, ByVal type As DataBuilderBase)
OutputLine(outputDescription)
type.FillRows()
OutputLine("")
End Sub
但要回答我自己的問題......我本可以做到這一點......
Private Sub DoSupplyModels()
DoSupplyModelType(Of Projections)("ITEM SUMMARIES")
DoSupplyModelType(Of DataBlocks)("DATA BLOCKS")
End Sub
Private Sub DoSupplyModelType(Of T as DataBuilderBase)(ByVal outputDescription As String, ByVal type As T)
OutputLine(outputDescription)
Dim type as New DataBuilderBase (_currentSupplyModel,_excelRows)
type.FillRows()
OutputLine("")
End Sub
是對的嗎?
賽斯
正如其他人所指出的,你不需要泛型來做你想做的事情,但我會回答技術問題的完整性:
Private Sub MyMethod(Of T As DataBuilderBase)(ByVal instance As T)
instance.FillRows()
End Sub
然后執行以下操作調用方法:
MyMethod(Of ItemSummaries)(new SupplyModel.ItemSummaries(...))
你可以重構利用共享基礎和使用多態的事實:( VB有點生疏,你應該明白)
你可以有一個方法:
Private Sub FillAndOutput(textToOutput as String, filler as DataBuilderBase)
OutputLine(string)
filler.FillRows()
OutputLine("")
end sub
你可以打電話給:
Private Sub DoSupplyModel
FillAndOutput("ITEM SUMMARIES",New SupplyModel.ItemSummaries(_currentSupplyModel, _excelRows))
FillAndOutput("NUMBERED INVENTORIES",New SupplyModel.NumberedInventories(_currentSupplyModel, _excelRows))
End Sub
在這種情況下,我不認為重構泛型函數是合理的,即使以重復自己為代價。 你有兩個選擇:
這些選項中的任何一個都涉及非常微不足道的工作而且收益很少(您將三行代碼轉換為一行)。
但是,為了回答您的問題,VB.NET使用of
關鍵字來指定泛型類型參數
Public Sub Foo(Of T)(argument as T)
...
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.