开发者

Initializing a new class in its own constructor

开发者 https://www.devze.com 2023-04-09 22:35 出处:网络
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

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 { g开发者_运维知识库et; set; }
}

Is this doable or am I barking up the wrong tree?


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 a User() which in turn constructs a User() and it is turtles all the way down.


You could use a lazy loaded method for your aggregated User class and not initialize it in the constructor:

public class User {
    private User _user;

    public User Associated 
    { 
        get
        {
            if (_user == null)
                _user = new User();
            return _user;
        }
    }
}


You are calling the User constructor recursively. Every time you new a User, it news another User ad infinitum (or rather, ad StackOverflowException).


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.


Calling the constructor inside the constructor leads you to an infinite loop:

Create a new User instance -> Create a new User instance -> Create a new User instance -> Create a new User instance -> Create a new User instance -> Create a new User instance...

You could do something like that:

public class User {
    public User() {

    }

    public AddAssociatedUser() {
        this.Associated = new User();
    }

    public User Associated { get; set; }
}

And call the AddAssociatedUser when you need it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号