开发者

How to reference parent in inline creation of objects?

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 the created parent in its own creation code?

Parent = new Parent(
{
    Name = "Parent",
    Chi开发者_如何转开发ld= new Child(/*ReferenceToParent*/)
});


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.


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;


No, because the reference starts referencing the allocated object after the constructor's execution has finished.


This is pretty old and it looks there is no new solution for this in newer C# version, does it? If so, please, share.

Meanwhile, I would like to add another solution kind of similar to the accepted one, but different. It assumes that you can change the Parent class.

using System;
public class Program
{
    public static void Main()
    {
        Parent p = new Parent()
        {
            Name = "Parent",
            Child = new Child()
        };
        
        Console.WriteLine(p.Child.Parent.Name);
    }
        
    public class Parent
    {
        public string Name {get; set;}
        
        public Child Child {
            get { return this._child; }
            set { 
                this._child = value; 
                if(value != null) 
                    value.Parent = this;
            }
        }
        private Child _child;
    }
    
    public class Child 
    {
        public Parent Parent {get; set;}
    }  
}

It can be executed in this link.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜