Книга: C# 2008 Programmer

Interface Casting

Interface Casting

In the preceding example, the IManager interface extends both the IPerson and IAddress interfaces. So an instance of the Manager class (which implements the IManager interface) will contain members defined in both the IPerson and IAddress interfaces:

Manager m1 = new Manager() {
 Name = "John", //---from IPerson---
 DateofBirth = new DateTime(l970, 7, 28), //---from IPerson---
 Dept = "IT", //---from IManager---
 Street = "Kingston Street", //---from IAddress---
 Zip = 12345 //---from IAddress---
};
Console.WriteLine(m1.Age()); //---from IPerson---
Console.WriteLine(m1.State()); //---from IAddress--- 

In addition to accessing the members of the Manager class through its instance (in this case m1), you can access the members through the interface that it implements. For example, since m1 is a Manager object that implements both the IPerson and IAddress interfaces, you can cast m1 to the IPerson interface and then assign it to a variable of type IPerson, like this:

//---cast to IPerson---
IPerson p = (IPerson) m1;

This is known as interface casting. Interface casting allows you to cast an object to one of its implemented interfaces and then access its members through that interface.

You can now access members (the Age() method and Name and DateofBirth properties) through p:

Console.WriteLine(p.Age());
Console.WriteLine(p.Name);
Console.WriteLine(p.DateofBirth);

Likewise, you can cast the m1 to the IAddress interface and then assign it to a variable to of type IAddress:

//---cast to IAddress---
IAddress a = (IAddress) m1;
Console.WriteLine(a.Street);
Console.WriteLine(a.Zip);
Console.WriteLine(a.State());

Note that instead of creating an instance of a class and then type casting it to an interface, like this:

Manager m2 = new Manager();
IPerson p = (IPerson) m2;

You can combine them into one statement:

IPerson p = (IPerson) new Manager();

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


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