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

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

Интервал:

Закладка:

Сделать

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---

l.LogError();

Abstract Classes versus Interfaces

An abstract class defines the members and optionally provides the implementations of each member. Members that are not implemented in the abstract class must be implemented by classes that inherit from it.

An interface, on the other hand, defines the signatures of members but does not provide any implementation. All the implementations must be provided by classes that implement it.

So which one should you use? There are no hard-and-fast rules, but here are a couple of points to note:

□ You can add additional members to classes as and when needed. In contrast, once an interface is defined (and implemented by classes), adding additional members will break existing code.

□ Classes support only single-inheritance but can implement multiple interfaces. So if you need to define multiple contracts (rules) for a type, it is always better to use an interface.

Summary

This chapter explained how inheritance works in C# and the types of inheritances available — implementation and interface. One important topic covered in this chapter is that of abstract class versus interface, both of which have their uses in C#.

The chapter also described how you can provide overloaded methods and operators, as well as add capabilities to a class without deriving from it by using the extension method feature new in C# 3.0.

Chapter 7

Delegates and Events

Two of the most important aspects of object-oriented programming are delegates and events. A delegate basically enables you to reference a function without directly invoking the function. Delegates are often used to implement techniques called callbacks, which means that after a function has finished execution, a call is made to a specific function to inform it that the execution has completed. In addition, delegates are also used in event handling. Despite the usefulness of delegates, it is a topic that not all .NET programmers are familiar with. An event, on the other hand, is used by classes to notify clients when something of interest has happened. For example, a Buttoncontrol has the Clickevent, which allows your program to be notified when someone clicks the button.

This chapter explores the following:

□ What is a delegate?

□ Using delegates

□ Implementing callbacks using a delegate

□ What are events?

□ How to handle and implement events in your program

Delegates

In C#, a delegate is a reference type that contains a reference to a method. Think of a delegate as a pointer to a function. Instead of calling a function directly, you use a delegate to point to it and then invoke the method by calling the delegate. The following sections explain how to use a delegate and how it can help improve the responsiveness of your application.

Creating a Delegate

To understand the use of delegates, begin by looking at the conventional way of invoking a function. Consider the following program:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Delegates {

class Program {

static void Main(string[] args) {

int num1 = 5;

int num2 = 3;

Console.WriteLine(Add(num1, num2).ToString());

Console.WriteLine(Subtract(num1, num2).ToString());

Console.ReadLine();

}

static int Add(int num1, int num2) {

return (num1 + num2);

}

static int Subtract(int num1, int num2) {

return (num1 - num2);

}

}

}

The program contains three methods: Main(), Add(), and Subtract(). Notice that the Add()and Subtract()methods have the same signature. In the Main()method, you invoke the Add()and Subtract()methods by calling them directly, like this:

Console.WriteLine(Add(num1, num2).ToString());

Console.WriteLine(Subtract(num1, num2).ToString());

Now create a delegate type with the same signature as the Add()method:

namespace Delegates {

class Program {

delegate int MethodDelegate(int num1, int num2);

static void Main(string[] args) {

...

You define a delegate type by using the delegatekeyword, and its declaration is similar to that of a function, except that a delegate has no function body.

To make a delegate object point to a function, you create an object of that delegate type ( MethodDelegate, in this case) and instantiate it with the method you want to point to, like this:

static void Main(string[] args) {

int num1 = 5;

int num2 = 3;

MethodDelegate method = new MethodDelegate(Add);

Alternatively, you can also assign the function name to it directly, like this:

MethodDelegate method = Add;

This statement declares method to be a delegate that points to the Add() method. Hence instead of calling the Add() method directly, you can now call it using the method delegate:

//---Console.WriteLine(Add(num1, num2).ToString());---

Console.WriteLine(method(num1, num2).ToString());

The beauty of delegates is that you can make the delegate call whatever function it refers to, without knowing exactly which function it is calling until runtime. Any function can be pointed by the delegate, as long as the function's signature matches the delegate's.

For example, the following statements check the value of the Operationvariable before deciding which method the methoddelegate to point to:

char Operation = 'A';

MethodDelegate method = null;

switch (Operation) {

case 'A':

method = new MethodDelegate(Add);

break;

case 'S':

method = new MethodDelegate(Subtract);

break;

}

if (method != null)

Console.WriteLine(method(num1, num2).ToString());

You can also pass a delegate to a method as a parameter, as the following example shows:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Delegates {

class Program {

delegate int MethodDelegate(int num1, int num2);

static void PerformMathOps(MethodDelegate method, int num1, int num2) {

Console.WriteLine(method(num1, num2).ToString());

}

static void Main(string[] args) {

int num1 = 5;

int num2 = 3;

char Operation = 'A';

MethodDelegate method = null;

switch (Operation) {

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

Интервал:

Закладка:

Сделать

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

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


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

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

x