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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

}

}

To implement an interface, you define your class and add a colon ( :) followed by the interface name:

public class Employee : IPerson

You then provide the implementation for the various members:

{

public string Name { get; set; }

public DateTime DateofBirth { get; set; }

public ushort Age() {

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

}

Notice that I'm using the new automatic properties feature (discussed in Chapter 4) in C# 3.0 to implement the Nameand DateofBirthproperties. That's why the implementation looks the same as the declaration in the interface.

As explained, all implemented members must have the publicaccess modifiers.

You can now use the class as you would a normal class:

Employee e1 = new Employee();

e1.DateofBirth = new DateTime(1980, 7, 28);

el.Name = "Janet";

Console.WriteLine(e1.Age()); //---prints out 28---

This could be rewritten using the new object initializer feature (also discussed in Chapter 4) in C# 3.0:

Employee el = new Employee() {

DateofBirth = new DateTime(1980, 7, 28),

Name = "Janet"

};

Console.WriteLine(e1.Age()); //---prints out 28---

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 IPersoninterface defines the basic information about a user, such as name and date of birth, while another interface such as IAddresscan 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 Employeeclass that implements both interfaces, like this:

public class Employee : IPerson, IAddress {

//---implementation here---

}

The full implementation of the Employeeclass 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 Employeeclass 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());

Extending Interfaces

You can extend interfaces if you need to add new members to an existing interface. For example, you might want to define another interface named IManagerto store information about managers. Basically, a manager uses the same members defined in the IPersoninterface, with perhaps just one more additional property — Dept. In this case, you can define the IManagerinterface by extending the IPersoninterface, like this:

interface IPerson {

string Name { get; set; }

DateTime DateofBirth { get; set; }

ushort Age();

}

interface IManager : IPerson {

string Dept { get; set; }

}

To use the IManagerinterface, you define a Managerclass that implements the IManagerinterface, like this:

public class Manager : IManager {

//---IPerson---

public string Name { get; set; }

public DateTime DateofBirth { get; set; }

public ushort Age() {

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

}

//---IManager---

public string Dept { get; set; }

}

The Managerclass now implements all the members defined in the IPersoninterface, as well as the additional member defined in the IManagerinterface. You can use the Managerclass like this:

Manager m1 = new Manager() {

Name = "John",

DateofBirth = new DateTime(1970, 7, 28),

Dept = "IT"

};

Console.WriteLine(m1.Age());

You can also extend multiple interfaces at the same time. The following example shows the IManagerinterface extending both the IPersonand the IAddressinterfaces:

interface IManager : IPerson, IAddress {

string Dept { get; set; }

}

The Managerclass now needs to implement the additional members defined in the IAddressinterface:

public class Manager : IManager {

//---IPerson---

public string Name { get; set; }

public DateTime DateofBirth { get; set; }

public ushort Age() {

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

}

//---IManager---

public string Dept { get; set; }

//---IAddress---

public string Street { get; set; }

public uint Zip { get; set; }

public string State() {

//---some implementation here---

return "CA";

}

}

You can now access the Managerclass like this:

Manager m1 = new Manager() {

Name = "John",

DateofBirth = new DateTime(1970, 7, 28),

Dept = "IT",

Street = "Kingston Street",

Zip = 12345

};

Console.WriteLine(m1.Age());

Console.WriteLine(m1.State());

Interface Casting

In the preceding example, the IManager interface extends both the IPersonand IAddressinterfaces. So an instance of the Managerclass (which implements the IManagerinterface) will contain members defined in both the IPersonand IAddressinterfaces:

Manager m1 = new Manager() {

Name = "John", //---from IPerson---

DateofBirth = new DateTime(l970, 7, 28), //---from IPerson---

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

Интервал:

Закладка:

Сделать

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

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


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

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

x