C# 属性

C# 抽象

C# 字符串

C# 泛型

C# 杂项

C# 新特性

C# 聚合(HAS-A 关系)

在 C# 中,聚合是一个类将另一个类定义为任何实体引用的过程。这是重用类的另一种方式。它是一种代表 HAS-A 关系的关联形式。

C# 聚合示例

让我们看一个聚合示例,其中 Employee 类将 Address 类的引用作为数据成员。这样,它可以重用 Address 类的成员。

例子 (Example)

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


上一主题 C# 继承 下一主题 没有了
  • 使用社交账号登录,本站支持
全部评论(0)