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

后端 未结 2 841
温柔的废话
温柔的废话 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}).

提交回复
热议问题