我有一个VB.NET函数,如下所示,传递给函数的参数'x'是Type'Single'。但是,我想编写函数,以便它可以接受任何数字类型,如'Single','Double'和'Integer'。我知道这样做的一种方法是编写具有相同名称的3个函数,但它会非常繁琐。谁能提出任何想法?谢谢。
Public Function Square(x As Single) As Single
Return x * x
End Function
答案 0 :(得分:8)
尝试以下方法
Public Function Square(Of T)(ByVal x As Object) As T
Dim b As Object = Val(x) * Val(x)
Return CType(b, T)
End Function
您可以使用上述功能
Dim p As Integer = Square(Of Integer)(10)
Dim d As Double = Square(Of Double)(1.5)
答案 1 :(得分:2)
您可以按IConvertible
和Structure
限制泛型类型。以下数据类型实现了IConvertible接口:
这里是对SLaks提供的链接中的代码的重写:
Public Function Square(Of T As {IConvertible, Structure})(x As T) As T
'TODO: If (GetType(T) Is GetType(Date)) Then Throw New InvalidOperationException()
Dim left As ParameterExpression = Expression.Parameter(GetType(T), "x")
Dim right As ParameterExpression = Expression.Parameter(GetType(T), "x")
Dim body As BinaryExpression = Expression.Multiply(left, right)
Dim method As Func(Of T, T, T) = Expression.Lambda(Of Func(Of T, T, T))(body, left, right).Compile()
Return method(x, x)
End Function
参考:https://jonskeet.uk/csharp/miscutil/usage/genericoperators.html
答案 2 :(得分:0)
代码允许通过Arg发布任何值,但只会处理数值。返回值必须为double,因为Val仅返回double。
Of T允许呈现通用对象类型。
Private Function sqr(Of T)(Arg As T) As Double
If IsNumeric(Arg) Then
Return Val(Arg) * Val(Arg)
Else
Return 0
End If
End Function