2012-04-30 81 views
1

我創建了一個自定義的值類型:不能設置「值」的自定義的值類型

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 

那麼,如何定義我的值類型(我知道這一定是簡單的,但我找不到任何地方
的一個實例!)操作符?

注意我不想考沿着以下(你需要重載=<>運營商都)線If v.Equals(x)

+1

[Visual Basic 2005中的運算符重載](http://msdn.microsoft.com/zh-cn/library/ms379613(v = vs .80).aspx) – Oded

回答

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 

Note: You'll probably want to implement IEquatable(Of MyValueType) as you'll gain some benefits from doing this and would be considered a "best practice."

+0

感謝Matt,Oded讓我開始了這些行。注意:'null'在VB.NET中是無效的語法 –

+0

@MattWilko,將心智上下文從C#切換到VB並不總是很容易。對於那個很抱歉。無論如何,我已經更新了這個例子,並且刪除了null(nothing)檢查,因爲它們不適用於struts。 – Matt

+0

謝謝 - 非常有用(順便說一句,我正在實現IEquatable,我剛剛發佈了一個代碼示例) –

相關問題