在C#中实现组合和聚合?

我如何/(在C#中实现组合和聚合的最佳方法是什么?)

谢谢123Developer

这是一个非常抽象的问题,因为组合和聚合都非常相似,并且在概念上实际上只是不同而不一定在代码级别。 (也就是说,你可能会认为一辆汽车有一个发动机组成,一只狗有跳蚤聚合,但如果你在代码中对它们进行建模,没有什么能阻止你以同样的方式实现它们)。

但是,如果你想分解差异并尝试并强行添加软件设计决策以突出这些差异,我想你可以做这样的事情……以维基百科为例 :

聚合与普通组成的不同之处在于它并不意味着所有权。 在组合中,当拥有对象被破坏时,包含的对象也被破坏。 在汇总中,这不一定是真的。 例如,一所大学拥有各个部门(例如化学),每个部门都有一些教授。 如果大学关闭,部门将不复存在,但这些部门的教授将继续存在。 因此,大学可以被视为一个部门的组合,而部门则有教授的集合。 此外,教授可以在多个部门工作,但是一个部门不能成为一个以上大学的一部分。

您可以构建此代码来表示它(使用尽可能多的人为的组合/聚合指示):

public class University : IDisposable { private IList departments = new List(); public void AddDepartment(string name) { //Since the university is in charge of the lifecycle of the //departments, it creates them (composition) departments.Add(new Department(this, name)); } public void Dispose() { //destroy the university... //destroy the departments too... (composition) foreach (var department in departments) { department.Dispose(); } } } public class Department : IDisposable { //Department makes no sense if it isn't connected to exactly one //University (composition) private University uni; private string name; //list of Professors can be added to, meaning that one professor could //be a member of many departments (aggregation) public IList Professors { get; set; } // internal constructor since a Department makes no sense on its own, //we should try to limit how it can be created (composition) internal Department(University uni, string name) { this.uni = uni; this.name = name; } public void Dispose() { //destroy the department, but let the Professors worry about //themselves (aggregation) } } public class Professor { } 

好吧,在垃圾收集的世界里,通过引用访问所有对象,严格组合和聚合之间的微妙差异(所有权)模糊了一点 – 所以一般 (当使用类时)它归结为另一个对象的字段或采集:

 class Building { private readonly List rooms = new List(); public IList Rooms {get {return rooms;}} public Address Address {get;set;} //... } class Address { public string Line1 {get;set;} public string PostCode {get;set;} //... } class Room { public string Name {get;set;} public int Capacity {get;set;} //... } 

如果我错过了这一点,请澄清……

在讨论struct时,事情会更复杂 – 但通常在谈论OO概念时, struct使用仅限于值字段……