[英]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.