[英]How to get/update property of parent object from child object
I have a class called Invoice 我有一门课叫做发票
public Invoice() {
this.ServiceId = 0;
this.Sections = new List<Section>();
}
I have another class called Sections 我还有另一节课
public Section() {
this.Items = new List<Item>();
}
and yet another class called Item 还有另一个叫做Item的类
public Item() {
blah, blah;
}
Now I am passing an object of Item into my windows user control, and I have the need to update the 'ServiceId' property located on my Invoice class. 现在,我将Item对象传递到Windows用户控件中,并且需要更新Invoice类上的'ServiceId'属性。 My question is there a way to edit that property from my item object?
我的问题是有没有办法从我的item对象编辑该属性? and how would I go about doing that.
以及我将如何去做。
Other information of note is that none of my classes inherit from anything. 其他需要注意的信息是,我的类都不继承任何东西。 Meaning that Item does not inherit from Section and Section not from Inspection.
表示项目不继承自“节”和“不继承自检查”。 They are simply list collections.
它们只是列表集合。 Thanks for your help.
谢谢你的帮助。
A good way to do this is through a hierarchical dependency injection. 一个很好的方法是通过分层依赖注入。 The
Section
class should have a constructor that requires an Invoice
and a Parent
or ParentInvoice
property: Section
类应具有一个需要Invoice
和Parent
或ParentInvoice
属性的构造函数:
public Section()
{
this.Items = new List<Item>();
public Invoice Parent { get; set; }
public Section(Invoice parent)
{
this.Parent = parent;
}
}
And likewise with the Item
; Item
也同样; it should require a Section
as a parent. 它应该要求一个
Section
作为父Section
。 Then from any item you will be able to use 然后,您将可以使用任何物品
Invoice i = this.Parent.Parent;
You can create methods that will add the sections and items like so: 您可以创建将添加节和项的方法,如下所示:
public Invoice()
{
//....
public Section AddSection()
{
var s = new Section(this);
Sections.Add(s);
return s;
}
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.