Delegate, Lambda expression, and event series 06. Use Action to implement observer mode and experience the difference between delegate and event. lambdaaction
In "two ways to implement the Observer Pattern", the Observer Pattern has been implemented through the interface, delegate, and event methods. This article uses Action to implement this mode and to experience the difference between delegation and events.
□Use Action to implement observer Mode
Let's take a football field as an example. When the referee blew the final whistle, the victory team celebrated and the Failure team fell. Think of the referee as the observer, and the two teams in the game as the observer.
As the observer, the referee must provide an Action delegate for the observer method registration.
public class Referee
{
public Action DoSth;
public void ISayGameOver()
{
Console. WriteLine ("click it... the game is over ~~ ");
DoSth();
}
}
The winning team and the failed team have a common base class.
public class Team
{
private string _name;
public Team(string name)
{
_name = name;
}
public string Name
{
get { return _name; }
}
}
A victory or failure Team, as an observer, must have a method that complies with the Action defined in Referee.
public class WinTeam : Team
{
public WinTeam(string name) : base(name){}
public void Celebrate()
{
Console. WriteLine ("We have been promoted, so happy! ");
}
}
public class LoseTeam : Team
{
public LoseTeam(string name) : base(name){}
public void WeAreSad()
{
Console. WriteLine ("the game is lost, so sad! ");
}
}
The client registers the methods of the failed and victory teams to the Action variable, and then triggers the delegate chain and method by a method of the observer.
static void Main(string[] args)
{
Referee referee = new Referee();
Var winTeam = new WinTeam ("Victory team ");
Var loseTeam = new LoseTeam ("failed teams ");
// Register the observer
referee.DoSth += winTeam.Celebrate;
referee.DoSth += loseTeam.WeAreSad;
// The event triggered by the observer notifies the observer
referee.ISayGameOver();
}
□Differences between experience delegation and events
Now, on the client, before calling the Referee instance method ISayGameOver, we try to set the Referee delegate variable dosomething to null.
static void Main(string[] args)
{
Referee referee = new Referee();
Var winTeam = new WinTeam ("Victory team ");
Var loseTeam = new LoseTeam ("failed teams ");
// Register the observer
referee.DoSth += winTeam.Celebrate;
referee.DoSth += loseTeam.WeAreSad;
referee.DoSth = null;
// The event triggered by the observer notifies the observer
referee.ISayGameOver();
}
It can be seen that when the Referee delegate variable dosomething is set to null, all registered methods will not be executed.
If you modify the Referee delegate variable dosomething as an event.
public class Referee
{
public event Action DoSth;
public void ISayGameOver()
{
Console. WriteLine ("click it... the game is over ~~ ");
if (DoSth != null)
{
DoSth();
}
}
}
It can be seen that after you modify the delegate variable dosomething as an event, you can only use the + = and-= registration and cancellation methods, but not the = setting.
Comment out referee. dosomething = null. No error will be reported.
"Delegation, Lambda expressions, and event series" include:
Delegate, Lambda expression, event series 01, Delegate, basic delegate usage, delegate Method and Target attribute delegate, Lambda expression, event series 02, when should I use delegate, Lambda expression, event series 03, from delegate to Lamda expression?
Delegation, Lambda expressions, event series 04, how the delegation chain is formed, multicast delegation, calling the delegation chain method, delegation chain Exception Handling delegation, Lambda expressions, event series 05, action delegate and closure delegate, Lambda expression, and event series 06. Use Action to implement observer mode and experience the differences between delegate and event
How to Use lambda in C # To handle delegate events
The delegate is defined as follows: copy the code as follows: public class SocketSp {public delegate void ReceiveCompleted (byte [] receiveBuffer, int etetotallen, Exception ex); public ReceiveCompleted receiveCompleted ;} the following copy code is defined by the Caller: public class LinkOuter {SocketSp linkOuterSocket = new SocketSp (); private void test (Socket requestHandleSocket) {// link linkOuterSocket here. receiveCompleted event. You also want to pass in the requestHandleSocket parameter for later processing .}} The first idea was to use delegate but failed. Although it is attached, the parameter passed by the delegate is lost and subsequent operations cannot be performed. Copy the Code as follows: private void test (Socket requestHandleSocket) {linkOuterSocket. receiveCompleted + = delegate {// To do};} The second idea is To use Action, and the result also fails. The IDE prompts that the delegated Action does not use three parameters. The copy code is as follows: private void test (Socket requestHandleSocket) {linkOuterSocket. receiveCompleted + = (Action) (outerReceiveBuffer, totalLen, ex) =>{// To do});} The third idea is To use lambda expressions To First connect To the delegate, at the same time, the call of local variables is used to transmit parameters to the sendResponse function for subsequent operations. The copy code is as follows: private void test (Socket requestHandleSocket) {linkOuterSocket. receiveCompleted + = new SocketSp. receiveCompleted (outerReceiveBuffer, totalLen, ex) => {byte [] realOuterReceiveBuffer = new byte [totalLen]; Array. copy (outerReceiveBuffer, 0, realOuterReceiveBuffer, 0, totalLen); sendResponse (requestHandleSocket, realOuterReceiveBuffer, "200 OK", "text/html ");});} finally, it is implemented using lambda expressions. Articles that you may be interested in: C # Use Lambda and delegate template Methods
Help lambda expressions and actions in C #
New Action (
() => WatchOutput. Items. Insert (
0, string. Format (formatString, parameters )))
It can be viewed:
Void Action1 ()
{
WatchOutput. Items. Insert (
0, string. Format (formatString, parameters ))
}
The advantage of anonymous delegation is that you can directly use variables in the method, such as formatString and parameters.