在 VB.NET 中,如果我想为不同类型的数值变量(Integer
, Long
, Decimal
, Double
)提供扩展方法,我总是必须为这些定义多个方法:
<Extension()> Public Function Add(a As Integer, b As Integer) As Integer
Return a + b
End Function
<Extension()> Public Function Add(a As Long, b As Long) As Long
Return a + b
End Function
<Extension()> Public Function Add(a As Double, b As Double) As Double
Return a + b
End Function
<Extension()> Public Function Add(a As Decimal, b As Decimal) As Decimal
Return a + b
End Function
现在对于一个单一的操作,这没问题,但是我想要创建的方法越多,我也需要做更多的重复。
有没有通用的方法呢?我很想看到这样的东西(伪代码):
<Extension()> _
Public Function Add(Of T As Numeric)(a As T, b As T) As T
Return a + b
End Function
或者有没有其他概念可以这样做?