在 C# 中,聚合是一个类将另一个类定义为任何实体引用的过程。这是重用类的另一种方式。它是一种代表 HAS-A 关系的关联形式。
让我们看一个聚合示例,其中 Employee 类将 Address 类的引用作为数据成员。这样,它可以重用 Address 类的成员。
using System; public class Address { public string addressLine, city, state; public Address(string addressLine, string city, string state) { this.addressLine = addressLine; this.city = city; this.state = state; } } public class Employee { public int id; public string name; public Address address;//Employee HAS-A Address public Employee(int id, string name, Address address) { this.id = id; this.name = name; this.address = address; } public void display() { Console.WriteLine(id + " " + name + " " + address.addressLine + " " + address.city + " " + address.state); } } public class TestAggregation { public static void Main(string[] args) { Address a1=new Address("G-13, Sec-3","Noida","UP"); Employee e1 = new Employee(1,"Sonoo",a1); e1.display(); } }
输出:
1 Sonoo G-13 Sec-3 Noida UP