АкушерствоАнатомияАнестезиологияВакцинопрофилактикаВалеологияВетеринарияГигиенаЗаболеванияИммунологияКардиологияНеврологияНефрологияОнкологияОториноларингологияОфтальмологияПаразитологияПедиатрияПервая помощьПсихиатрияПульмонологияРеанимацияРевматологияСтоматологияТерапияТоксикологияТравматологияУрологияФармакологияФармацевтикаФизиотерапияФтизиатрияХирургияЭндокринологияЭпидемиология

Delegates in C#

Delegates are the.NET version of addresses to methods. For example, each student on the final exams has the definite place. Student is the variable and the definite place is the link or address of this variable. You can call the method by its name and also you can call it by its delegate. Compare this to C++, where function pointers are nothing more than a pointer to a memory location that are not type - safe. You have no idea what a pointer is really pointing to, and items such as parameters and return types are not known. This is completely different with.NET; delegates are type - safe classes that define the return types and types of parameters. The delegate class not only contains a reference to a method, but can hold references to multiple methods. So, then you need to know how to declare it?! You have to start by defining the delegates you want to use. Defining delegates means telling the compiler what kind of method a delegate of that type will represent. Then, you have to create one or more instances of that delegate. Behind the scenes, the compiler creates a class that represents the delegate. The syntax for defining delegates looks like this:

delegate double MathAction(double num);

One good way of understanding delegates is by thinking of a delegate as something that gives a name to a method signature and the return type.

Delegates are implemented as classes derived from the class System.MulticastDelegate, which is derived from the base class System.Delegate. The C# compiler is aware of this class and uses its delegate syntax to shield you from the details of the operation of this

class. This is another good example of how C# works in conjunction with the base classes to make programming as easy as possible.

So, the following is the simple example of using the delegates:

delegate double MathAction(double num);

class DelegateTest

{ static double Double(double input)

{ return input * 2;}

static void Main()

{ MathAction ma = Double;

double multByTwo = ma(4.5);

Console.WriteLine("multByTwo: {0}", multByTwo);}

// Output: multByTwo: 9 }

48.Lambda expressions in C#

Lambda expressions are directly related to delegates. When the parameter is a delegate type, you can use a Lambda expression to implement a method that ’ s referenced from the delegate. To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator =>, and you put the expression or statement block on the other side. For example, the lambda expression x => x * x specifies a parameter that’s named x and returns the value of x squared. You can assign this expression to a delegate type:

delegate int del(int i);

static void Main(string[] args)

{ del myDelegate = x => x * x;

int j = myDelegate(5); //j = 25}

With Lambda expressions there are several ways to define parameters. If there’s only one parameter, just the name of the parameter is enough.(x=>x*x). If a delegate uses more than one parameter, you can combine the parameter names inside brackets ((x,y)=>x*y).

If the Lambda expression consists of a single statement, a method block with curly brackets and a return statement is not needed. Func<double, double> square = x => x * x;

It’s completely legal to add curly brackets, a return statement, and semicolons. Usually it’s just easier to

read without: del square = x =>

{return x * x;}

However, if you need multiple statements in the implementation of the Lambda expression, curly bracketsand the return statement are required:

del lambda = param = >

{param += mid;

param += " and this was added to the string.";

return param;}.Here is the simple example of using lambda expressions:

delegate double MathAction(double num);class Mydelegate{ static void Main() { MathAction ma = s => s * s * s; double cube = ma(2.0); Console.WriteLine("cube: {0}", cube); } // Output: cube: 8.0}

49. Events in C#

Events are based on delegates and offer a publish/subscribe mechanism to delegates. You can find events everywhere across the framework. In Windows applications, the Button class offers the Click event.

This type of event is a delegate. A handler method that is invoked when the Click event is fired needs to be defined, with the parameters as defined by the delegate type. So, events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.

To declare an event inside a class, first a delegate type for the event must be declared, if none is already declared.

public delegate void Del (object sender, EventArgs e);

The delegate type defines the set of arguments that are passed to the method that handles the event. Multiple events can share the same delegate type, so this step is only necessary if no suitable delegate type has already been declared. Next, the event itself is declared.

public event ChangedEventHandler Changed;

An event is declared like a field of delegate type, except that the keyword event precedes the event declaration, following the modifiers. So, event publisher is the part of code that generates the events. Event listener is the part of code that process them. It’s usually a set of methods. And they communicate via delegates.

Here is the simple example of using events:


Дата добавления: 2015-09-18 | Просмотры: 620 | Нарушение авторских прав



1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 |



При использовании материала ссылка на сайт medlec.org обязательна! (0.004 сек.)