如何在内联对象创建中引用父对象? [英] How to reference parent in inline creation of objects?
问题描述
比方说,我有一个父/子关系ob对象,并尝试内联创建一个父对象(我不太确定这是正确的词).可以在其自己的创建代码中引用创建的父对象吗?
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",
Child= new Child(/*ReferenceToParent*/)
});
推荐答案
唯一的解决办法是让 Parent
构造函数调用 Child
构造函数本身并传递在 this
中.然后,您的对象初始化程序(这是我假设您要尝试的操作)可以在子级上设置其他属性:
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;
}
}
然后:
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.
这篇关于如何在内联对象创建中引用父对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!