简体   繁体   中英

Call parent in constructor c#

I want to do something like this:

Parent parent = new Parent(new Child(parent));

VS tells me parent is unknown variable.

I don't want such initialization:

Parent parent = new Parent();
Child child=new Child(parent);
parent.Child=child;

Is it possible ?

Thanks in advance for your help.

If you think about it, you're trying to pass to child your parent while you're actually trying to create parent in the first place. When you do new Child() , parent doesn't exist yet, so there is nothing to pass in.

What you can do however is this:

class Parent
{
    public Child CreateChild()
    {
         return new Child(this)
    }
}

and thus:

Parent parent = new Parent();
Child child= parent.CreateChild();

A better solution might be to have a constructor in Parent that creates the child for you:

public class Parent
{
    public Child {get; set;}

    public Parent()
    {
        Child = new Child(this);
    }
}

Thy this

public class Parent
{
    public Parent(Child ch)
    {
        this.Child = ch;
        this.Child.Parent = this;
    }

    public Child Child {get; set;}
}

Initialization:

Parent parent = new Parent(new Child());

What you want to do is impossible. Best guess for what you want, without more informations, is to have the parent constructor instantiate the child, sending it 'this'.

class Parent
{
  public Parent()
  {
     _child = new Child(this);
  }
   private Child _child;
}

Even if the syntax were possible, parent wouldn't have a useful value until after the call (it's probably null ). You would need to set a new value, anyway.

The closest equivalent to that process I can think of would be for the Parent class to create the Child inside its constructor, passing itself to the Child constructor. Then it can set its own .child member to that resulting object and you have the structure you want.

How about this:

public class Parent
{
    private IList<Child> _children = new List<Child>();

    public Parent() {} // probably don't want to hide default ctor

    public Parent(Child c)
    {
        AddChild(c);
    }

    public Parent AddChild(Child c)
    {
        c.Parent = this;
        _children.Add(c);
        return this;
    }

    public IList<Child> Children { get { return _children; } }
}

public class Child
{
    public Parent Parent { get; set; }
}

Then you could do this:

Parent parent = new Parent()
    .AddChild(new Child())
    .AddChild(new Child());

Or

Parent parent = new Parent(new Child())
    .AddChild(new Child());

You have flexibility

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM