Книга: C# 2008 Programmer

Implementing Multiple Interfaces

Implementing Multiple Interfaces

A class can implement any number of interfaces. This makes sense because different interfaces can define different sets of behaviors (that is, members) and a class may exhibit all these different behaviors at the same time.

For example, the IPerson interface defines the basic information about a user, such as name and date of birth, while another interface such as IAddress can define a person's address information, such as street name and ZIP code:

interface IAddress {
 string Street { get; set; }
 uint Zip { get; set; }
 string State();
}

An employee working in a company has personal information as well as personal address information, and you can define an Employee class that implements both interfaces, like this:

public class Employee : IPerson, IAddress {
 //---implementation here---
}

The full implementation of the Employee class looks like this:

public class Employee : IPerson, IAddress {
 //---IPerson--- 
 public string Name { get; set; }
 public DateTime DateofBirth { get; set; }
 public ushort Age() {
  return (ushort)(DateTime.Now.Year - this.DateofBirth.Year);
 }
 //---IAddress---
 public string Street { get; set; }
 public uint Zip { get; set; }
 public string State() {
  //---some implementation here---
  return "CA";
 }
}

You can now use the Employee class like this:

Employee e1 = new Employee() {
 DateofBirth = new DateTime(1980, 7, 28),
 Name = "Janet",
 Zip = 123456,
 Street = "Kingston Street"
};
Console.WriteLine(e1.Age());
Console.WriteLine(e1.State());

Оглавление книги


Генерация: 1.260. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз