在自己的构造函数中初始化一个新类
我有一个用户类。其中一个属性需要是“关联”用户,因此它的类型需要是 User。现在,当我初始化该类时,当它尝试初始化关联属性时,我会遇到堆栈溢出。当前代码:
public class User {
public User() {
this.Associated = new User();
}
public User Associated { get; set; }
}
这是可行的还是我找错了树?
I have a User class. One of the properties needs to be an "associated" user, so it's type needs to be User. Right now when I initialize the class, I get a stack overflow when it tries to initialize the Associated property. Current code:
public class User {
public User() {
this.Associated = new User();
}
public User Associated { get; set; }
}
Is this doable or am I barking up the wrong tree?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
User.Associated 是否必须在构造时填充?如果你从构造函数中删除赋值,你不应该得到这样的结果。
您得到 SO 的原因是因为当您构造
User()
时,它构造了一个User()
,而后者又构造了一个User()
> 一路下来都是海龟。Does User.Associated have to be populated on construction? If you remove the assignment from the constructor you shouldn't get SO.
The reason you are getting an SO is because when you construct a
User()
it constructs aUser()
which in turn constructs aUser()
and it is turtles all the way down.您可以为聚合的
User
类使用延迟加载方法,而不是在构造函数中初始化它:You could use a lazy loaded method for your aggregated
User
class and not initialize it in the constructor:您正在递归调用
User
构造函数。每次您新
一个用户
时,它就会无限地新
另一个用户
(或者更确切地说,广告StackOverflowException
)。You are calling the
User
constructor recursively. Every time younew
aUser
, itnew
s anotherUser
ad infinitum (or rather, adStackOverflowException
).不要在构造函数中初始化关联成员。如果您只在需要时初始化它,我认为堆栈溢出应该消失。
Do not initialize the Associated member in the constructor. If you only initialize it when you need it, I think the stack overflow should go away.
问题是你已经开发了无限循环的新用户。每个新用户都会获得一个新用户作为同事。
我将从默认构造函数中删除分配,然后将其添加为公共属性。这样做可以让您控制何时分配同事,并防止无限循环。
The problem is that you've developed an endless loop of new users. Each new user gets a new user as an associate.
I would remove the assignement from the default constructor, then add it as a public property. Doing this will allow you to control when associates are assigned, and will prevent the endless loop.
在构造函数内调用构造函数会导致无限循环:
创建一个新的
User
实例 ->创建一个新的User
实例 ->创建一个新的User
实例 ->创建一个新的User
实例 ->创建一个新的User
实例 ->创建一个新的User
实例...您可以执行类似的操作:
并在需要时调用
AddAssociatedUser
。Calling the constructor inside the constructor leads you to an infinite loop:
Create a new
User
instance -> Create a newUser
instance -> Create a newUser
instance -> Create a newUser
instance -> Create a newUser
instance -> Create a newUser
instance...You could do something like that:
And call the
AddAssociatedUser
when you need it.