entrust

What is a delegate?

A delegate is a reference type (essentially a class that inherits the MulticastDelegate special class). Represents a reference to a method with a specific parameter list and return type.

Each delegate provides Invoke methods, BeginInvoke and EndInvoke asynchronous methods

Why do WE need delegates?

  • Delegates can take methods (that is, logic) as arguments;
    • Logic decouples and remains stable.
    • Code reuse to ensure project specification.

How do I use delegates?

How do you declare, instantiate, and use delegates

Commissioned by the statement

delegate void Del(string str);
static void Notify(string name)
{
    Console.WriteLine($"Notification received for: {name}");
}
Copy the code

Instantiate delegate

Del del1 = new Del(Notify);
//C# 2.0
Del del2 = Notify;
Copy the code

The delegate

Del1. Invoke (" Ming "); Del2 (" Ming ");Copy the code

Other uses delegate

//C# 2.0 uses anonymous methods to declare and instantiate delegates. Del del3 = delegate(string name) {console. WriteLine($"Notification received for: {name}"); }; //C# 3.0 uses lambda expressions to declare and instantiate delegate Del del4 = name => {console. WriteLine($"Notification received for: {name}"); };Copy the code

To simplify the development process,.NET includes a set of delegate types:

  • Action<> takes parameters and returns no value.
  • Func<> has an argument and returns the value of the type specified by the argument.
  • Predicate<> is used to determine whether the parameters satisfy the delegate condition.

The actual case

Code:

Class Program {/// <summary> // <param name="fullName"></param> private delegate void KillDelegate(string fullName); Static void Main(string[] args) {killWithKnifeDelegate = new KillDelegate(KillWithKnife); Kill(" Kill ", killWithKnifeDelegate); var killWithSwordDelegate = new KillDelegate(KillWithSword); Kill(" yellow ", killWithSwordDelegate); var killWithAxeDelegate = new KillDelegate(KillWithAxe); Kill(" Ouyang ", killWithAxeDelegate); Console.ReadKey(); } static void Kill(string fullName, KillDelegate KillDelegate) {console. WriteLine($"{fullName} "); Killdelegate.invoke (fullName); // Invoke killdelegate.invoke (fullName); Console.WriteLine($"{fullName} increment 10 experience "); } static void KillWithKnife(string fullName) {console. WriteLine($"{fullName} kill monster with knife "); } static void KillWithSword(string fullName) {console. WriteLine($"{fullName} KillWithSword "); } static void KillWithAxe(string fullName) {Console.WriteLine($"{fullName} axe "); }}Copy the code

Lambda expressions

What is Lambda?

Lambda is just a more convenient syntax for using delegates.

//C# 2.0 uses anonymous methods to declare and instantiate delegates. Del del3 = delegate(string name) {console. WriteLine($"Notification received for: {name}"); }; //C# 3.0 uses lambda expressions to declare and instantiate delegate Del del4 = name => {console. WriteLine($"Notification received for: {name}"); };Copy the code

Why Lambda?

Simplify the development process without affecting performance.

How do I use Lambda?

Basic form of lambda:

// Parentheses are optional only if the lambda has only one input argument; Otherwise parentheses are required (input-parameters) => expressionCopy the code

Use empty parentheses to specify zero input parameters:

Action line = () => Console.WriteLine();
Copy the code

Two or more input parameters in parentheses are separated by commas:

Func<int, int, bool> testForEquality = (x, y) => x == y;
Copy the code

Statements lambda

(input-parameters) => { <sequence-of-statements> }
Copy the code

The body of a lambda statement can contain any number of statements;

Action<string> greet = name => { string greeting = $"Hello {name}!" ; Console.WriteLine(greeting); }; greet("World"); // Output: // Hello World!Copy the code

Using anonymous delegate and lambda code:

public static void Main(string[] args) { List<int> list = new List<int>(); for (int i = 1; i <= 100; i++) { list.Add(i); List<int> result = list.findall (delegate (int no) {return (no % 2 == 0); }); foreach (var item in result) { Console.WriteLine(item); } // Lambda List<int> result = list.findall (I => I % 2 == 0); foreach (var item in result) { Console.WriteLine(item); }}Copy the code

The event

What is the event?

An event is a special type of delegate used primarily for the delivery of messages or notifications. Events can only be invoked from the event’s publication type and are typically based on the EventHandler delegate, which has an object representing the event sender and a class derived from System.Eventargs that contains data about the event.

When to use delegates and events?

  • Listening events are optional: if your code must call code provided by the subscriber, use a delegation-based design. If your code can do all its work without calling any subscribers, use event-based design.
  • Return values require delegates: Delegates for events all have invalid return types, and the event handler passes information back to the event source by modifying the properties of the event parameter object.
  • Events have dedicated calls: classes other than the class that contains the event can only add and remove event listeners; Only classes that contain events can invoke events.

How are events used?

Publish event

Defining event data

public class CustomEventArgs : EventArgs { public CustomEventArgs(string message) { Message = message; } public string Message { get; set; }}Copy the code

Declare events in the publish class

public delegate void CustomEventHandler(object sender, CustomEventArgs args); public event CustomEventHandler RaiseCustomEvent; Public Event EventHandler<CustomEventArgs> RaiseCustomEvent;Copy the code

Subscribe to the event

Define an event handler method

void HandleCustomEvent(object sender, CustomEventArgs a)  
{  
   // Do something useful here.  
} 
Copy the code

Add subscription events using (+=)

publisher.RaiseCustomEvent += HandleCustomEvent;  
Copy the code

Unsubscribe events with (-=)

publisher.RaiseCustomEvent -= HandleCustomEvent;  
Copy the code

The sample

using System; Namespace DotNetEvents {public class CustomEventArgs: EventArgs { public CustomEventArgs(string message) { Message = message; } public string Message { get; set; Public Event EventHandler<CustomEventArgs> RaiseCustomEvent; public Event EventHandler<CustomEventArgs> RaiseCustomEvent; public void DoSomething() { RaiseCustomEvent(new CustomEventArgs("Event triggered")); }} // Class Subscriber {private readOnly string _id; public Subscriber(string id, Publisher pub) { _id = id; RaiseCustomEvent += HandleCustomEvent; } // Define an event handler method. void HandleCustomEvent(object sender, CustomEventArgs e) { Console.WriteLine($"{_id} received this message: {e.Message}"); } } class Program { static void Main() { var pub = new Publisher(); var sub1 = new Subscriber("sub1", pub); var sub2 = new Subscriber("sub2", pub); // Call the method that raises the event pub.dosomething (); Console.ReadKey(); }}}Copy the code

reference

  • Entrust docs.microsoft.com/zh-cn/dotne…
  • Lambda expressions docs.microsoft.com/zh-cn/dotne…
  • Event docs.microsoft.com/zh-cn/dotne…