Reputation: 320
I have a problem with an Generic Class and define the operator overloads associated with it. Question:
How do I set the operator for the following class assuming that the DataType will be any of the numeric types {float,double,Integer,etc.}?
I quite don't understand the concept yet
Public Class Nombre(Of DataType) '' aka Number
'VALUE
Private _Value As DataType
Public Property Value As DataType
Get
Return Me._Value
End Get
Set(value As DataType)
Me._Value = value
End Set
End Property
Public Sub New(value As DataType)
Me._Value = value
End Sub
Public Sub Add(x As DataType)
_Value += x
End Sub
Public Sub Subs(x As DataType)
_Value -= x
End Sub
Public Sub Mult(x As DataType)
_Value = _Value * x
End Sub
Public Sub Power(x As DataType)
_Value = _Value ^ x
End Sub
Public Sub inc()
_Value += 1
End Sub
Public Sub dec()
_Value -= 1
End Sub
Public Sub Divide(x As DataType)
_Value = _Value / x
End Sub
End Class
Upvotes: 3
Views: 3672
Reputation: 172270
How do I set the operator for the following class assuming that the DataType will be any of the numeric types {float,double,Integer,etc.}?
You can't do that in a type-safe way, since you cannot restrict DataType
to classes where +
, -
, etc. are defined. This is a commonly requested feature which is just not available yet.
You will have to create an IntegerNombre
class, a DoubleNombre
class, etc. Then you can define operator overloads in the usual way:
Public Shared Operator +(ByVal n1 As IntegerNombre,
ByVal n2 As IntegerNombre) As IntegerNombre
Return New IntegerNombre(n1._Value + n2._Value)
End Operator
(Of course, you could keep your generic class, turn Option Strict Off
and use late binding with Object
:
_Value = DirectCast(_Value, Object) + x
...but you really shouldn't.)
Upvotes: 4