如何为自己的类定义'='?

Dil*_*ger 0 vb.net

我创建了一个这样的类:

 Public Class WorkDay            

    <JsonProperty("start")>
    Public Property starttime As String = Nothing
    <JsonProperty("end")>
    Public Property endtime As String = Nothing
    Public Property breaks As New List(Of Break)

End Class
Run Code Online (Sandbox Code Playgroud)

现在我需要比较此类的一个对象,例如:

Dim working_plan = JsonConvert.DeserializeObject(Of Dictionary(Of String, WorkDay))(wp)
Dim DayNames = {"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}
Dim this_day = working_plan(day)

If this_day = Nothing Then
   ...
Run Code Online (Sandbox Code Playgroud)

Nowthis_day是类的一个对象WorkDay,所以当我尝试与任何东西进行比较时,我得到:

没有为WorkDay类型定义运算符=。

我应该在我自己的类中定义运算符吗?我怎样才能做到这一点?

Ale*_* B. 5

编辑:编辑说我应该在回答问题之前仔细阅读问题;)要检查一个对象是否为 Nothing,您必须使用Is相应的IsNot关键字:

    If this_day Is Nothing Then
Run Code Online (Sandbox Code Playgroud)

各自:

   If this_day IsNot Nothing Then
Run Code Online (Sandbox Code Playgroud)

比较并非什么都没有的对象的原始答案:

在 WorkDay 类中重载等于运算符:

Public Shared Operator =(x As WorkDay, y As WorkDay)
       'Code to determine whetther x equals y
End Operator
Run Code Online (Sandbox Code Playgroud)

请注意,您还必须重载不等于运算符:

Public Shared Operator <>(x As WorkDay, y As WorkDay)
      'Code to determine whetther x not equals y
End Operator
Run Code Online (Sandbox Code Playgroud)

关于马格努斯的评论:

Public Overrides Function Equals(obj As Object) As Boolean
    Dim o As WorkDay = TryCast(obj, WorkDay)
    If o IsNot Nothing Then
        'check whether o equals Me
    Else
        Return False
    End If
End Function

Public Overrides Function GetHashCode() As Integer
    'return a feasible hashcode of a member of Me e.g.
     Return Me.StartTime.GetHashCode() XOR Me.EndTime.GetHashCode() 
End Function
Run Code Online (Sandbox Code Playgroud)