Common Classes (T) - An indication from the VB.Net type range

This is the code I'm trying to develop:

  Public Structure Statistic(Of t)
        Dim maxStat As t
        Dim curStat As t

        Public Sub New(ByVal pValue As t)
            maxStat = pValue
            curStat = pValue
        End Sub

        Public Property Level() As t
            Get
                Return curStat
            End Get
            Set(ByVal value As t)
                curStat = value
                If curStat > maxStat Then curStat = maxStat
            End Set
        End Property
    End Structure

It will not compile because I get an error message that '>' is not defined for the types T and T. In any case, can I specify restrictions that guarantee that T is of a numerical type?

This is what I mean after changes and suggestions from users. It still does not work. Do I need to change the T values โ€‹โ€‹for everyone so that they are IComparable? There must be something really simple that I'm picking on.

   Public Structure Statistic(Of T As IComparable(Of T))
        Dim maxStat As T
        Dim curStat As T

        Public Sub New(ByVal pValue As T)
            maxStat = pValue
            curStat = pValue
        End Sub

        Public Property Statistic() As T
            Get
                Return curStat
            End Get
            Set(ByVal value As T)
                If value > maxStat Then

                End If
            End Set
        End Property
    End Structure
+2
source share
2 answers

Here you go ... this should work.

Public Structure Statistic(Of t As {IComparable})
   Dim maxStat As t
   Dim curStat As t

   Public Sub New(ByVal pValue As t)
      maxStat = pValue
      curStat = pValue
   End Sub

   Public Property Level() As t
      Get
            Return curStat
      End Get
      Set(ByVal value As t)
            curStat = value
            If curStat.CompareTo(maxStat) > 0 Then curStat = maxStat
      End Set
   End Property
End Structure

, , , . ( ) ( ), : Public Structure Statistic(Of t As {Structure, IComparable}).

+4

T IComparable. , , curStat maxStat CompareTo, , .

+7

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


All Articles