A comprehensive explanation: the commission, events

Each programmer in the project must not open around the topic: delegates and events. For starters, always feel somewhat difficult to understand, or can not use their own free. In this paper, we commissioned to do a detailed explanation of the event, that is the foundation of self-knowledge to ponder, but also a record. Some long length, if read carefully, I believe you will be harvested.

"Introducing Visual C # 2010" (Adam Freeman with, Apress Publishing) Chapter 10 of the book in such a description:

Delegates are special types thatencapsulate a method, similar to function pointers found in other programminglanguages. Delegates have a number of uses in C#, but you are most likely toencounter a special type of delegate—the event. Events make notifyinginterested parties simple and flexible, and I’ll explain the convention fortheir use later in the chapter.

Delegate is a special type of packaging method is similar to the function pointers in other programming languages. We commissioned extensive use in C #, but you most likely to encounter is a special delegate type - event. Event notification so that the relevant part of the simple and flexible, and its use will be explained later in this chapter convention.

I’ll also explain the Func and Action typesthat let you use delegates in a more convenient form and that are usedextensively in some of the latest C# language features, such as parallelprogramming. We’ll finish up this chapter with a look at anonymous methods andlambda expressions, two C# features that let us implement delegates withouthaving to define methods in our classes.

I will explain Func and Action types, which allows you to use a more convenient form of commission, but also in some of the latest C # properties are also widely used, such as parallel programming. The chapter concludes investigation anonymous methods and lambda expressions, this way we do not delegate can use both C # properties defined in the class method.

 

Commission:

The delegate definition: a function as a parameter to another function call. Another explanation: When a class or the process needs to call another method, it needs additional classes or processes invoked, this mechanism is called delegation. Online Daniel said: Trust can be understood as function pointers, except that the delegates are object-oriented, type-safe.

Implementation steps:

1. Declare a delegate type:

public delegate int CalculateDelegate(int x, int y);

2, define a delegate object:

CalculateDelegate calculateDelegate = new CalculateDelegate(Add);

Add a method wherein delegate package;

3, the implementation of the delegate method:

calculateDelegate(2, 3);

Which method delegates binding Add:

public static int Add(int x, int y)
{ return x + y;}

 

event:

Event is a special type of delegate

Double-click the button to get winform illustrate commission may be more appropriate:

Declare a delegate, and declare an event:

public delegate void EventHandler(object sender, EventArgs e);
public event EventHandler Click;

Bind an event:

this.button1.Click += new System.EventHandler(this.button1_Click);

this.button1_Click is a method:

private void button1_Click(object sender, EventArgs e){}

 

Take a real project example:

Anonymous method:

Anonymous method (Anonymous methods), a code block as a delegate parameter passed in the art. Anonymous method is not only the name of the method body. In the anonymous method, you do not need to specify a return type, it is the return statement in the method body inferred.

Explaining written binding method delegate before:

CalculateDelegate calculateDelegate = new CalculateDelegate(Add);
public static int Add(int x, int y)
{
return x + y;
}

If you are using an anonymous method to rewrite the code above:

CalculateDelegate calculateDelegate = delegate(int x, int y){return x + y;};

Visible: anonymous method to bind directly commissioned by eliminating the need to write a single method, making the code more concise.

Project, when using delegates, many times the editor will help us put directly into the appropriate method in the delegate object, but sometimes the editor will not help us, such as: Control.Dispatcher.Invoke (delegate) such as:

this.btnExit .Dispatcher .Invoke (new Action(() => {}));

 

Lambda expressions:

Lambda expressions is an anonymous function, simply put, it is not a statement of the method, ie no access modifier, return values ​​statement and name;

Lambda expressions of C # operator using a Lambda =>, the operator is read as "goes to". The syntax is as follows:

(object argOne, object argTwo) => {; /*Your statement goes here*/}

Examples of the use of anonymous commission to rewrite the above method written on the basis of anonymous methods, Lambda expressions used to write the following:

method one:

CalculateDelegate calculateDelegate = (int x, int y) => { return x + y; };

Second way, a simpler expression:

CalculateDelegate calculateDelegate = (x, y) => { return x + y; };

Three ways, could not be easier:

CalculateDelegate calculateDelegate = (x, y) => x + y;

As can be seen from the above, Lambda is only on the basis of anonymous methods on the plus => symbol, but it puts the entire code to implement even more elegant. 

 

Generic delegate:

Microsoft has a built-in generic delegate in .net platform, such as: Action, Action <T>, Fun <T> and so on. Actual use, if you need to use generic delegate, delegate system is built will be able to basically meet the demand, and following their prototypes introduced one by one and calls instance.

Action

Action requesting system package, no parameter has no return value. Call examples:

public delegate void Action();
static void Main(string[] args)       
{
  Action action = new Action(Method);
  action();
}
private static void Method()
{
  Console.WriteLine("i am is a action");
}

If the method is simple expression, Lambda expressions may be used, as follows: 

Action action = () => { Console.WriteLine("i am is a action"); };

 

Action<T>

System package Action <T> delegate, but there is no return value parameters. Call examples:

public delegate void Action<in T1, in T2>(T1 arg1, T2 arg2);
static void Main(string[] args)        
{
  Action<int,int> action = new Action<int,int>(Method);
  action(2,3);
}
private static void Method(int x,int y)
{
  Console.WriteLine("i am is a action");
}

 

Lambda expressions prepared using Action <T> code is as follows:

Action<int, int> action = (x, y) => { Console.WriteLine("i am is a action"); };

 

Fun<T>

System package Fun <T> delegate, return a value. Call examples:

public delegate TResult Fun<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
static void Main(string[] args) 
{
  Fun<int, int, bool> fun = new Fun<int, int, bool>(Method);
  bool ret = fun(2,3);
}
private static bool Method(int x,int y)
{

  if (x + y == 5) return true;
  else return false;
}

 

Lambda expressions prepared using Fun <T>, the following code:

Fun<int, int, bool> fun = (x, y) =>            
{
  if (x + y == 5) return true;
  else return false;
};

 

Fun <T> where there are no return values ​​of the parameters:

Fun < BOOL > Fun = () =>     
{
  int X = . 4 ;
  int Y = . 3 ;
  IF (X + Y == . 5 ) return to true ;
  the else return to false ;
}; // may be written so Fun <bool> fun = () => false;

  

Multicast delegate:

Finally said multicast delegate, the so-called multicast delegate, the "multicast delegates" (MulticastDelegate). It can be seen from its name, such as delegate can broadcast the same information would affect the "spread" to all sides. Multicast has a method invocation list of the delegate, delegate when called, it will call the method in the list one by one in order to achieve multiple effects. Relatively simple, temporarily illustrated.

 

In this paper for the time being come to an end, if you want to see more articles, please pay attention to the "small project notes," No public;

If in doubt: You can join the QQ group number: 732 982 683

 

Guess you like

Origin www.cnblogs.com/ysyn/p/12012517.html