这是我正在努力开发的代码:
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
它无法编译,因为我收到错误'>'没有为T和T的类型定义。无论如何我可以指定保证T是数字类型的约束吗?
这是我在用户的更改和建议之后的目前所拥有的。它仍然无法正常工作。我是否必须将T的值更改为IComparable?必须有一些非常简单的东西,我搞砸了。
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
答案 0 :(得分:7)
您可以将T约束为IComparable。这样你知道curStat和maxStat都有一个CompareTo方法,你可以用它来确定一个是否大于另一个。
答案 1 :(得分:4)
你去......这应该有用。
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})
。