开发者

Generic Classes (T) - Specifying from a Range of Types VB.Net

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 won't compile because I'm getting an error that '>' is not defined for types of T and T. Is there anyway I can specify constraints that guarentee that T is of a numeric type?

This is what I currently have after changes and suggestions from the users. It's still not working. Do I have to change the values of T for all of them to be IComparable? There must be something really simple that I'm screwing up.

   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 Stati开发者_JAVA技巧stic() As T
            Get
                Return curStat
            End Get
            Set(ByVal value As T)
                If value > maxStat Then

                End If
            End Set
        End Property
    End Structure


You could constrain T to IComparable. That way you know that curStat and maxStat both have a CompareTo method you can use to determine if one is greater than the other.


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

Also, you mentioned constraining to numerics, but I don't think you can constrain to just that. You can however constrain to just primitive types (on the stack) and not allow objects (on the heap) by doing this: Public Structure Statistic(Of t As {Structure, IComparable}).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜