1

我创建了一个自定义 ValueType:

Private Structure MyValueType
    Private _integerValue As Integer

    Public Sub New(initValue As Integer)
        _integerValue = initValue
    End Sub

    Public Overrides Function ToString() As String
        Return _integerValue.ToString
    End Function
End Structure

但我不知道如何测试这样的值:

    Dim v As New MyValueType(3)
    Dim x As New MyValueType(4)

    If v = x Then 'fails compile
        MessageBox.Show("The values are the same")
    End If

错误:

Operator '='  is not defined for Types MyValueType and MyValueType

那么如何为我的 ValueType 定义运算符(我知道这一定很简单,但我在任何地方都找不到示例!)?

注意我不想测试If v.Equals(x)

4

1 回答 1

1

类似于以下内容(您需要重载 the=<>运算符):

Sub Main
    Dim v As New MyValueType(3)
    Dim x As New MyValueType(4)

    If v <> x Then 'fails compile
        Console.WriteLine("The values are not the same")
    End If    
End Sub

Private Structure MyValueType
    Private _integerValue As Integer

    Public Sub New(initValue As Integer)
        _integerValue = initValue
    End Sub

    Public Overrides Function ToString() As String
        Return _integerValue.ToString
    End Function

    Public Shared Operator =(
        ByVal left as MyValueType, 
        ByVal right as MyValueType) As Boolean

        If left.ToString() = right.ToString()
            Return True
        End If

        Return False   
    End Operator 

    Public Shared Operator <>(
        ByVal left as MyValueType, 
        ByVal right as MyValueType) As Boolean          

        Return Not (left = right)   
    End Operator     
End Structure

注意:您可能希望实施IEquatable(Of MyValueType),因为这样做会获得一些好处,并且会被视为“最佳实践”。

于 2012-04-30T12:25:25.947 回答