How to configure VB.NET parameters as universal type?

I have a VB.NET function, as shown below, the 'x' parameter that is passed to the function is of type 'Single'. However, I want to write a function so that it can accept any numeric types, such as "Single", "Double" and "Integer". I know that one way to do this is to write three functions with the same name, but that would be so tedious. Can anyone suggest any idea? Thanks.

Public Function Square(x As Single) As Single Return x * x End Function 
+5
source share
3 answers

try the 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 the above function like

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

You can restrict the generic type with IConvertible and Structure . The following data types implement 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 is 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 

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

+2
source

The code allows any value to be placed through Arg, but only numeric values ​​will be processed. The return value must be double, because Val returns double only.

The T allows you to use common object types.

  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 
0
source

Source: https://habr.com/ru/post/1200075/


All Articles