我有2个classess。像这样的角色和用户
角色
Public Class Role
Public Property RoleID As Integer
Public Property CreatedBy As User
Sub New()
If Me.CreatedBy Is Nothing Then
Me.CreatedBy = New User()
End If
End Class
用户
Public Class User
Public Property UserID As Integer
Public Property Role As Role
Public Sub New()
If Me.Role Is Nothing Then
Me.Role = New Role()
End If
End Sub
End Class
情况就像我们创建角色一样,我们将保存创建此角色的人员。所以我有一个类型为User的CreatedBy属性。类似地,当我们创建用户时,我们将提到新用户所属的角色。因此,我有一个名为“角色”的属性“角色”。当我创建User类的对象时,这个循环引用给我StackOverflow异常作为递归。
我该如何处理?我应该恢复我的诱惑吗?怎么样?
答案 0 :(得分:2)
在每个类中创建构造函数重载以传递宿主对象:
Public Class User
Public Property UserID As Integer
Public Property Role As Role
Public Sub New()
Me.Role = New Role(Me)
End Sub
Public Sub New(oRole As Role)
Me.Role = Role
End Sub
End Class
Public Class Role
Public Property RoleID As Integer
Public Property CreatedBy As User
Sub New()
Me.CreatedBy = New User(Me)
End Sub
Public Sub New(oUser As User)
Me.CreatedBy = oUser
End Sub
End Class