我创建了一个这样的类:
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
现在我需要比较这个类的对象,例如:
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
...
现在this_day
是WorkDay
类的对象,所以当我尝试与之比较时,我得到:
未为
WorkDay
类型定义operator =。
我应该在自己的班级中定义运算符?我怎么能这样做?
答案 0 :(得分:4)
编辑:编辑说我应该在回答问题前仔细阅读问题;)
要检查对象是否为Nothing,您必须使用Is
repsective IsNot
关键字:
If this_day Is Nothing Then
所属:
If this_day IsNot Nothing Then
比较不是什么的对象的原始答案:
在WorkDay类中重载等于运算符:
Public Shared Operator =(x As WorkDay, y As WorkDay)
'Code to determine whetther x equals y
End Operator
请注意,您还必须重载非等于运算符:
Public Shared Operator <>(x As WorkDay, y As WorkDay)
'Code to determine whetther x not equals y
End Operator
关于马格努斯的评论:
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