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

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

Интервал:

Закладка:

Сделать

You need only provide the implementation for the width property here. The implementation for the Area()and Perimeter()methods is inherited from the Squareclass.

The last implementation is the ICircleinterface, for which you will implement the radiusproperty as well as the Perimeter()and Area()methods:

public class Circle : ICircle {

public double radius { get; set; }

public double Perimeter() {

return (2 * Math.PI * (this.radius));

}

//---provide the implementation for the virtual method---

public double Area() {

return (Math.PI * Math.Pow(this.radius, 2));

}

}

Figure 6-10 shows the classes that you have implemented for these three interfaces.

Figure 610 Explicit Interface Members Implementation A class can implement - фото 120

Figure 6-10

Explicit Interface Members Implementation

A class can implement one or more interfaces. To implement a member in an interface, you simply need to match the member name and its signature with the one defined in the interface. However, there are times when two interfaces may have the same member name and signature. Here's an example:

public interface IFileLogging {

void LogError(string str);

}

public interface IConsoleLogging {

void LogError(string str);

}

In this example, both IFileLoggingand IConsoleLogginghave the same LogError()method. Suppose that you have a class named Calculationthat implements both interfaces:

public class Calculation : IFileLogging, IConsoleLogging {}

The implementation of the LogError()method may look like this:

public class Calculation : IFileLogging, IConsoleLogging {

//---common to both interfaces---

public void LogError(string str) {

Console.WriteLine(str);

}

}

In this case, the LogError()method implementation will be common to both interfaces and you can invoke it via an instance of the Calculationclass:

Calculation c = new Calculation();

//---prints out: Some error message here---

c.LogError("Some error message here");

In some cases, you need to differentiate between the two methods in the two interfaces. For example, the LogError()method in the IFileLogginginterface may write the error message into a text file, while the LogError()method in the IConsoleLogginginterface may write the error message into the console window. In that case, you must explicitly implement the LogError()method in each of the two interfaces. Here's how:

public class Calculation : IFileLogging, IConsoleLogging {

//---common to both interfaces---

public void LogError(string str) {

Console.WriteLine(str);

}

//---only available to the IFileLogging interface---

void IFileLogging.LogError(string str) {

Console.WriteLine("In IFileLogging: " + str);

}

//---only available to the IConsoleLogging interface---

void IConsoleLogging.LogError(string str) {

Console.WriteLine("In IConsoleLogging: " + str);

}

}

This example has three implementations of the LogError()method:

□ One common to both interfaces that can be accessed via an instance of the Calculationclass.

□ One specific to the IFileLogginginterface that can be accessed only via an instance of the IFileLogginginterface.

□ One specific to the IConsoleLogginginterface that can be accessed only via an instance of the IConsoleLogginginterface.

You cannot use the publicaccess modifier on the explicit interface methods' implementation.

To invoke these implementations of the LogError()method, use the following statements:

//---create an instance of Calculation---

Calculation c = new Calculation();

//---prints out: Some error message here---

c.LogError("Some error message here");

//---create an instance of IFileLogging---

IFileLogging f = c;

//---prints out: In IFileLogging: Some error message here---

f.LogError("Some error message here");

//---create an instance of IConsoleLogging---

IConsoleLogging l = c;

//---prints out: In IConsoleLogging: Some error message here---

l.LogError("Some error message here");

Another use of explicit interface member implementation occurs when two interfaces have the same method name but different signatures. For example:

public interface IFileLogging {

void LogError(string str);

}

public interface IConsoleLogging {

void LogError();

}

Here, the LogError()method in the IFileLogginginterface has a string input parameter, while there is no parameter in the IConsoleLogginginterface. When you now implement the two interfaces, you can provide two overloaded LogError()methods, together with an implementation specific to each interface as illustrated here:

public class Calculation : IFileLogging, IConsoleLogging {

//---common to both interfaces---

public void LogError(string str) {

Console.WriteLine("In LogError(str): " + str);

}

public void LogError() {

Console.WriteLine("In LogError()");

}

//---only available to the IFileLogging interface---

void IFileLogging.LogError(string str) {

Console.WriteLine("In IFileLogging: " + str);

}

//---only available to the IConsoleLogging interface---

void IConsoleLogging.LogError() {

Console.WriteLine("In IConsoleLogging");

}

}

As you can see , the first two LogError()methods are overloadedand are common to both interfaces. This means that you can access them via an instance of the Calculationclass. The next two implementations are specific to the IFileLoggingand IConsoleLogging interfaces and can be accessed only via an instance of each interface:

//---create an instance of Calculation---

Calculation c = new Calculation();

//---prints out: In LogError()---

c.LogError();

//---prints out: In LogError(str)---

c.LogError("Some error message here");

//---create an instance of IFileLogging---

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

Интервал:

Закладка:

Сделать

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

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


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

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

x