How to reference parent in inline creation of objects?

前端 未结 3 766
清歌不尽
清歌不尽 2021-01-20 13:54

Let\'s say I have a parent/child-relationship ob objects and try to create a parent object inline (I\'m not really sure that\'s the right word). Is it possible to reference

3条回答
  •  一向
    一向 (楼主)
    2021-01-20 14:41

    The only way round this would be for the Parent constructor to call the Child constructor itself and pass in this. Your object initializer (which is what I assume you're trying to do) could then set other properties on the child:

    public class Parent
    {
        public Child Child { get; private set; }
        public string Name { get; set; }
    
        public Parent()
        {
            Child = new Child(this);
        }
    }
    
    public class Child
    {
        private readonly Parent parent;
        public string Name { get; set; }
    
        public Child(Parent parent)
        {
            this.parent = parent;
        }
    }
    

    Then:

    Parent parent = new Parent
    {
        Name = "Parent name",
        // Sets the Name property on the existing Child
        Child = { Name = "Child name" }
    };
    

    I would try to avoid this sort of relationship though - it can get increasingly tricky as time goes on.

提交回复
热议问题