如何从子对象 get/update 属性 父对象

How to get/update property of parent object from child object

我有一个 class 叫做 Invoice

public Invoice() {
        this.ServiceId = 0;
        this.Sections = new List<Section>();            
    }

我还有一个 class 叫做 Sections

public Section() {
        this.Items = new List<Item>();
    }

还有一个 class 叫做 Item

public Item() {
        blah, blah;
    }

现在我将 Item 对象传递到我的 windows 用户控件中,我需要更新位于我的发票 class 上的 'ServiceId' 属性 .我的问题是有没有办法从我的项目对象中编辑 属性?我该怎么做。

其他值得注意的信息是我的 class 中的 none 继承自任何东西。这意味着 Item 不继承自 Section 而 Section 不继承自 Inspection。它们只是列表集合。感谢您的帮助。

执行此操作的一个好方法是通过分层依赖项注入。 Section class 应该有一个需要 InvoiceParentParentInvoice 属性:

的构造函数
public Section() 
{
    this.Items = new List<Item>();

    public Invoice Parent { get; set; }

    public Section(Invoice parent) 
    {
        this.Parent = parent;
    }
}

Item 同样如此;它应该需要 Section 作为 parent。然后你可以从任何项目中使用

Invoice i = this.Parent.Parent;

您可以像这样创建添加部分和项目的方法:

public Invoice()
{
    //....
    public Section AddSection()
    {
        var s = new Section(this);
        Sections.Add(s);
        return s;
    }
    //...
}