【问题标题】:VB.NET (Of T) Comparison OperatorVB.NET (Of T) 比较运算符
【发布时间】:2010-10-03 16:19:51
【问题描述】:

在示例代码中,带有“错误注释”的行给出了以下错误 -

  • 没有为类型“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

【问题讨论】:

    标签: vb.net generics .net-2.0 operator-overloading


    【解决方案1】:

    为什么 VB 不自动调用合适的 T 操作符? (即如果 T 是整数,则调用整数比较函数。)

    因为对 T 没有任何约束可以确保它具有适当的运算符。您可以要求 T 为 IComparable,并使用它的 CompareTo 方法。

    【讨论】:

    • 谢谢马克。我一直在思考 C++ 和运算符重载。不确定哪种方式更清洁/更优雅。猜猜这是语言设计的问题。
    • 您也可以在 VB 中重载运算符,但您必须告诉编译器它才能将其与泛型类型一起使用。
    • @Joel - 我认为操作重载没有通用约束
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    相关资源
    最近更新 更多