gpt4 book ai didi

vb.net - 数值类型的通用方法

转载 作者:行者123 更新时间:2023-12-04 04:46:28 25 4
gpt4 key购买 nike

在 VB.NET 中,如果我想为不同类型的数值变量( IntegerLongDecimalDouble )提供扩展方法,我总是必须为这些定义多种方法:

<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

或者有没有其他概念可以这样做?

最佳答案

这是无法做到的,因为您不能将泛型类型限制为一组数字类型( IntegerLongDecimalDouble )。问题是没有IArithmetic可以用来约束 T 的接口(interface)到,因此你不能这样写:

' This does not work because IArithmetic does not exist
<Extension()> _
Public Function Add(Of T As IArithmetic)(a As T, b As T) As T
Return a + b
End Function

但是,您可以通过 Microsoft Feedback Center 加入说服 Microsoft 实现此计划的事业。并就类似请求提出和/或评论。

关于vb.net - 数值类型的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18103705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com