VB.NET 我的类属性最终出现在循环引用中,因此出现 StackOverflow 异常

发布于 2024-12-25 21:30:45 字数 774 浏览 3 评论 0原文

我有2节课。 Role 和 User 这样的

Role

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

User

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 属性。同样,当我们创建用户时,我们会提到新用户属于什么角色。所以我有一个名为“Role”类型的“Role”属性。当我创建 User 类的对象时,这个循环引用给了我 StackOverflow 异常作为其递归。

我该如何处理这个问题?我应该重组我的实体吗?如何 ?

I have 2 classess. Role and User like this

Role

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

User

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

The situation is like when we create roles, we will save who created this role. So i have a CreatedBy Property of type User. Similarly when we create a User, we will mention what role the new user belongs to .So i have a property called "Role" of type "Role". This circular reference giving me StackOverflow exception as its recursive when i create an object of User class.

How do i handle this ? should i restucture my entties ? how ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

赠佳期 2025-01-01 21:30:45

在每个类中创建构造函数重载以传递宿主对象:

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

Create constructor overloads in each of your classes to pass the host object:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文