Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

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 Managerclass through its instance (in this case m1), you can access the members through the interface that it implements. For example, since m1is a Managerobject that implements both the IPersonand IAddressinterfaces, you can cast m1to the IPersoninterface 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 Nameand DateofBirthproperties) through p:

Console.WriteLine(p.Age());

Console.WriteLine(p.Name);

Console.WriteLine(p.DateofBirth);

Likewise, you can cast the m1to the IAddressinterface 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();

The is and as Operators

Performing a direct cast is safe only if you are absolutely sure that the object you are casting implements the particular interface you are trying to assign to. Consider the following case where you have an instance of the Employeeclass:

Employee e1 = new Employee();

The Employeeclass implements the IPersonand IAddressinterfaces. And so if you try to cast it to an instance of the IManagerinterface, you will get a runtime error:

//---Error: Invalid cast exception---

IManager m = (IManager) e1;

To ensure that the casting is done safely, use the isoperator. The isoperator checks whether an object is compatible with a given type. It enables you to rewrite the casting as:

if (m1 is IPerson) {

IPerson p = (IPerson) m1;

Console.WriteLine(p.Age());

Console.WriteLine(p.Name);

Console.WriteLine(p.DateofBirth);

}

if (m1 is IAddress) {

IAddress a = (IAddress) m1;

Console.WriteLine(a.Street);

Console.WriteLine(a.Zip); Console.WriteLine(a.State());

}

if (e1 is IManager) {

IManager m = (IManager) e1;

}

Using the isoperator means that the compiler checks the type twice — once in the isstatement and again when performing the actual casting. So this is actually not very efficient. A better way would be to use the asoperator.

The asoperator performs conversions between compatible types. Here's the preceding casting rewritten using the asoperator:

IPerson p = m1 as IPerson;

if (p != null) {

Console.WriteLine(p.Age());

Console.WriteLine(p.Name);

Console.WriteLine(p.DateofBirth);

}

IAddress a = m1 as IAddress;

if (a != null) {

Console.WriteLine(a.Street);

Console.WriteLine(a.Zip);

Console.WriteLine(a.State());

}

Employee e1 = new Employee();

//---m is null after this statement---

IManager m = e1 as IManager;

if (m != null) {

//...

}

If the conversion fails, the as operator returns null, so you need to check for nullbefore you actually use the instance of the interface.

Overriding Interface Implementations

When implementing an interface, you can mark any of the methods from the interface as virtual. For example, you can make the Age()method of the Employeeclass virtualso that any other classes that inherit from the Employeeclass can override its implementation:

public interface IPerson {

string Name { get; set; }

DateTime DateofBirth { get; set; }

ushort Age();

}

public class Employee : IPerson {

public string Name { get; set; }

public DateTime DateofBirth { get; set; }

public virtual ushort Age() {

return (ushort)(DateTime.Now.Year - this.DateofBirth.Year);

}

}

Suppose there is a new class called Directorthat inherits from the Employeeclass. The Directorclass can override the Age()method, like this:

public class Director : Employee {

public override ushort Age() {

return base.Age() + 1;

}

}

Notice that the Age()method increments the age returned by the base class by 1. To use the Directorclass, create an instance of it and set its date of birth as follows:

Director d = new Director();

d.DateofBirth = new DateTime(1970, 7, 28);

When you print out the age using the Age()method, you get 39 (2008–1970=38; increment it by 1 and the result is 39):

Console.WriteLine(d.Age()); //---39---

This proves that the overriden method in the Age()method is invoked. If you typecast d to the IPersoninterface, assign it to an instance of the IPersoninterface, and invoke the Age()method, it will still print out 39:

IPerson p = d as IPerson;

Console.WriteLine(p.Age()); //---39---

An interesting thing happens if, instead of overriding the Age()method in the Directorclass, you create a new Age()class using the newkeyword:

public class Director : Employee {

public new ushort Age() {

return (ushort)(base.Age() + 1);

}

}

Create an instance of the Directorclass and invoke its Age()method; it returns 39, as the following statements show:

Director d = new Director();

d.DateofBirth = new DateTime(1970, 7, 28);

Console.WriteLine(d.Age()); //---39---

However, if you typecast d to an instance of the IPersoninterface and then use that interface to invoke the Age()method, you get 38 instead:

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x