无法设置自定义ValueType的“值”

时间:2012-04-30 10:49:12

标签: .net vb.net value-type

我创建了一个自定义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)

1 个答案:

答案 0 :(得分:1)

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

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),因为您可以从中获得一些好处,并被视为“最佳做法”。