How to reference parent in inline creation of objects?

前端 未结 3 756
清歌不尽
清歌不尽 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:27

    You can't do this because an instance of Parent has not been created yet. If child requires an instance of Parent in it's constructor you must create one. Create an instance of Parent first, then Child passing in the parent to the Constructor, and then assign the instance of child to the property on Parent.

    var parent = new Parent
    {
      Name = "Parent",
      //More here...
    };
    var child = new Child(parent);
    parent.Child = child;
    

提交回复
热议问题