📅  最后修改于: 2020-10-31 03:04:30             🧑  作者: Mango
在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