繁体   English   中英

如何在类中创建泛型方法?

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

基本上,您需要指定T将是实现FillRows方法的基类型的子类。 在C#中,这看起来就是这样

private void myFunction<T>( T someList ) where T : DataBuilderBase {
    someList.FillRows();
}

在MSDN上找到了一个VB.NET 示例

编辑和凯文是对的,这可能会更好地处理多态。

在这种情况下,我不认为重构泛型函数是合理的,即使以重复自己为代价。 你有两个选择:

  1. 重构您的代码,以便它允许无参数构造函数并在更高的继承级别创建一个函数,允许您指定当前传递给构造函数的参数。
  2. 使用显式反射来实例化泛型类型并将这些参数传递给构造函数。

这些选项中的任何一个都涉及非常微不足道的工作而且收益很少(您将三行代码转换为一行)。

但是,为了回答您的问题,VB.NET使用of关键字来指定泛型类型参数

Public Sub Foo(Of T)(argument as T)
   ...
End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM