在构造函数c#中调用parent

Alp*_*age 0 c#

我想做这样的事情:

Parent parent = new Parent(new Child(parent));
Run Code Online (Sandbox Code Playgroud)

VS告诉我父母是未知变量.

我不想要这样的初始化:

Parent parent = new Parent();
Child child=new Child(parent);
parent.Child=child;
Run Code Online (Sandbox Code Playgroud)

可能吗 ?

在此先感谢您的帮助.

LB2*_*LB2 6

如果您考虑一下,那么当您真正尝试创建父母时,您正试图将孩子传给孩子.当你这样做时new Child(),父母还不存在,所以没有什么可以传递的.

你可以做的是:

class Parent
{
    public Child CreateChild()
    {
         return new Child(this)
    }
}
Run Code Online (Sandbox Code Playgroud)

因此:

Parent parent = new Parent();
Child child= parent.CreateChild();
Run Code Online (Sandbox Code Playgroud)


Mat*_*and 6

更好的解决方案可能是让一个构造函数Parent为您创建子代:

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

    public Parent()
    {
        Child = new Child(this);
    }
}
Run Code Online (Sandbox Code Playgroud)