如何在内联对象创建中引用父对象? [英] How to reference parent in inline creation of objects?

查看:56
本文介绍了如何在内联对象创建中引用父对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个父/子关系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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆