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

后端 未结 2 839
温柔的废话
温柔的废话 2021-01-22 09:08

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 pValu         


        
相关标签:
2条回答
  • 2021-01-22 09:51

    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 讨论(0)
  • 2021-01-22 09:51

    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.

    0 讨论(0)
提交回复
热议问题