2012-04-30 26 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,我刚刚发布了一个代码示例) –

相关问题