3
在示例代码,用“错误注释”行给出了以下的错误 -VB.NET(OF T)比较运算符
- 运算符“<”不是类型“T”和定义'T'。
为什么VB不会自动调用适当的T运算符? (即,如果T是整数,则称为整数比较函数)。
是否有可能以优雅的方式使这项工作成为可能?
这是针对.NET 2.0的。
编辑 - 任何感兴趣的人的更新代码。
Public Class TreeNode(Of T)
Public Left As TreeNode(Of T)
Public Right As TreeNode(Of T)
Public Value As IComparable(Of T)
Public Sub New(ByVal _value As T)
Value = _value
End Sub
End Class
Public Class Tree(Of T)
Private _Root As TreeNode(Of T)
Public ReadOnly Property Root()
Get
Return _Root
End Get
End Property
Public Sub New()
_Root = Nothing
End Sub
Public Function Add(ByVal value As IComparable(Of T)) As TreeNode(Of T)
If _Root Is Nothing Then
_Root = New TreeNode(Of T)(value)
Else
Dim node As TreeNode(Of T) = _Root
While node IsNot Nothing
If value.CompareTo(node.Value) < 0 Then
If node.Left IsNot Nothing Then
node = node.Left
Else
node.Left = New TreeNode(Of T)(value)
Return node.Left
End If
Else
If node.Right IsNot Nothing Then
node = node.Right
Else
node.Right = New TreeNode(Of T)(value)
Return node.Right
End If
End If
End While
End If
Return _Root
End Function
Public Sub Print(ByVal node As TreeNode(Of T))
If node IsNot Nothing Then
Print(node.Left)
Console.WriteLine(node.Value)
Print(node.Right)
End If
End Sub
End Class
谢谢马克。我一直在考虑C++和运算符重载。不知道哪种方式更清洁/更优雅。猜猜这是语言设计的问题。 – user50612 2009-01-27 02:47:02