How to make Parameters of VB.NET function as Generic type?

≯℡__Kan透↙ 提交于 2020-07-06 11:53:17

问题


I have a VB.NET function as below, the parameter 'x' that is passed to the function is of Type 'Single'. However, I want to write the function so that it can accept any numeric type such as 'Single', 'Double' and 'Integer'. I know one way of doing that is to write 3 functions with the same names, but it would be so tedious. Can anyone suggest any idea? Thank you.

Public Function Square(x As Single) As Single
  Return x * x
End Function

回答1:


try following method

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

You can use above function like this

Dim p As Integer = Square(Of Integer)(10)
Dim d As Double = Square(Of Double)(1.5)



回答2:


You can constrain the generic type by IConvertible and Structure. The following data types implements the IConvertible interface:

  • System.Boolean
  • System.Byte
  • System.Char
  • System.DateTime
  • System.DBNull
  • System.Decimal
  • System.Double
  • System.Enum
  • System.Int16
  • System.Int32
  • System.Int64
  • System.SByte
  • System.Single
  • System.String
  • System.UInt16
  • System.UInt32
  • System.UInt64

Here's a rewrite of the code found in the link provided by 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

Reference: https://jonskeet.uk/csharp/miscutil/usage/genericoperators.html




回答3:


The code allows any value to posted via Arg but only numeric values will be processed. The returned value must be double because Val returns double only.

The Of T allows for generic object types to be presented.

   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


来源:https://stackoverflow.com/questions/25255014/how-to-make-parameters-of-vb-net-function-as-generic-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!