For the most part , A delegate is a class , This class maintains a field inside , Point to a method . Events can be treated as variables of a delegate type , Register by event 、 Cancel multiple delegates or methods . This article implements several methods through delegates and events , To understand the difference between the two .

□ Through delegated execution method

 class Program
 {
 static void Main(string[] args)
 {
 Example example = new Example();
 example.Go();
 Console.ReadKey();
 }
 }

 public class Example
 {
 public delegate void DoSth(string str);

 internal void Go()
 {
 // Declare a delegate variable , And take the known method as the parameter of its constructor
 DoSth d = new DoSth(Print);

 string str = "Hello,World";

 // Static methods through delegation Invoke Trigger delegation
 d.Invoke(str);
 }

 void Print(string str)
 {
 Console.WriteLine(str);
 }
 }

above ,

○ stay CLR Runtime , entrust DoSth It's actually just a class , This class has a constructor whose parameter type is method , And provides a Invoke Example method , Used to trigger the execution of a delegate .
○ entrust DoSth The parameters and return types of the method are defined
○ Through an authorized DoSth Constructor for , You can assign a method that meets the definition to a delegate
○ Call the instance method of the delegate Invoke Implemented the method

but , There's actually another way to delegate execution methods , That's it : Delegate variable ( parameter list )

 public class Example
 {
 public delegate void DoSth(object sender, EventArgs e);

 internal void Go()
 {
 // Declare a delegate variable , And take the known method as the parameter of its constructor
 DoSth d = new DoSth(Print);

 object sender = 10;
 EventArgs e = new EventArgs();

 d(sender, e);
 }

 void Print(object sender, EventArgs e)
 {
 Console.WriteLine(sender);
 }
 }

above ,

○ entrust DoSth Parameter list and method of Print The parameter list of is still consistent
○ entrust DoSth Parameters in object sender Usually used to indicate the initiator of an action ,EventArgs e Used to represent the parameters of the action .

But in fact , Delegate variable ( parameter list ), Events are executed in this way .

□ Through the event execution method

 public class Example
 {
 public delegate void DoSth(object sender, EventArgs e);
 public event DoSth myDoSth;

 internal void Go()
 {
 // Declare a delegate variable , And take the known method as the parameter of its constructor
 DoSth d = new DoSth(Print);

 object sender = 10;
 EventArgs e = new EventArgs();

 myDoSth += new DoSth(d);
 myDoSth(sender, e);
 }

 void Print(object sender, EventArgs e)
 {
 Console.WriteLine(sender);
 }
 }

above ,

○ Declared the event myDoSth, The type of event is DoSth This Commission
○ adopt += Register delegates for events
○ adopt DoSth The constructor of the delegate registers the delegate instance for the event
○ Take the delegate variable ( parameter list ) This form , Let the event execute the method

and , adopt += You can also register multiple delegates for events .

 public class Example
 {
 public delegate void DoSth(object sender, EventArgs e);
 public event DoSth myDoSth;

 internal void Go()
 {
 // Declare a delegate variable , And take the known method as the parameter of its constructor
 DoSth d = new DoSth(Print);
 DoSth d1 = new DoSth(Say);

 object sender = 10;
 EventArgs e = new EventArgs();

 // Register multiple delegates for events
 myDoSth += new DoSth(d);
 myDoSth += new DoSth(d1);

 myDoSth(sender, e);
 }

 void Print(object sender, EventArgs e)
 {
 Console.WriteLine(sender);
 }

 void Say(object sender, EventArgs e)
 {
 Console.WriteLine(sender);
 }
 }

above , adopt += Register for events 1 One or more delegate instances , actually , You can also register methods directly for events .

 public class Example
 {
 public delegate void DoSth(object sender, EventArgs e);
 public event DoSth myDoSth;

 internal void Go()
 {
 object sender = 10;
 EventArgs e = new EventArgs();

 // Register multiple delegates for events
 myDoSth += Print;
 myDoSth += Say;

 myDoSth(sender, e);
 }

 void Print(object sender, EventArgs e)
 {
 Console.WriteLine(sender);
 }

 void Say(object sender, EventArgs e)
 {
 Console.WriteLine(sender);
 }
 }

□ adopt EventHandler Execution method

First look EventHandler Source code .

so ,EventHandler Is commissioned . Use now EventHandler To perform multiple methods .

 public class Example
 {
 public event EventHandler myEvent;

 internal void Go()
 {
 object sender = 10;
 EventArgs e = new EventArgs();

 // Register multiple delegates for events
 myEvent += Print;
 myEvent += Say;

 myEvent(sender, e);
 }

 void Print(object sender, EventArgs e)
 {
 Console.WriteLine(sender);
 }

 void Say(object sender, EventArgs e)
 {
 Console.WriteLine(sender);
 }
 }

summary :
○ A delegate is a class , You can also instantiate , Assign a method to a delegate instance through the delegate's constructor
○ Trigger delegate has 2 Ways of planting : Delegate instance .Invoke( parameter list ), Delegate instance ( parameter list )
○ An event can be seen as a delegate type variable
○ adopt += Register multiple delegate instances or methods for events
○ adopt -= Unregister multiple delegate instances or methods for events
○ EventHandler It's a commission

C# More about the difference between delegation and event in

  1. C# The difference between delegation and event in instance analysis

    This article mainly introduces C# The difference between delegation and event in , In the form of examples, it shows the method of executing through delegate and the method of executing through event , And the related implementation process and principle analysis , Friends in need can refer to An example of this paper analyzes C# The difference between delegation and event in , Share with you ...

  2. entrust 、Lambda expression 、 Event series 06, Use Action Implement observer mode , Experience the difference between delegation and event

    stay " Implement observer mode (Observer Pattern) Of 2 Ways of planting " in , Once through the interface . The delegate and event approach implements the observer pattern . This experience uses Action Implement this pattern , And experience delegation and events from it ...

  3. c# The difference between a delegate and an event

    The difference between a delegate and an event There is no comparison between delegation and event , Because delegates are data types , Events are objects ( It can be understood as encapsulation of delegate variables .), The following is the object of delegation ( Events implemented by delegation ) and ( The standard event How to achieve ) The difference between events . Inside the event ...

  4. c# The difference between Commission and event

    1. What is a delegate , I won't introduce you here , If you want to know more, you can check the blog :http://www.cnblogs.com/xiaoxiaogogo/p/3571494.html Let's begin with an introduction to the event 1. Define events and ...

  5. c# Delegate and event in ( turn )

    C# Delegate and event in introduction entrust and The incident happened in .Net Framework It is widely used in , However , Better understanding of delegates and events to many contacts C# It's not easy for people who don't have a long time . They're like a fence , People who have passed this threshold , I think it's true ...

  6. c# The difference between delegation and event in

    Delegate has the same function as event class Dem5 { public Action deHandler; public event Action eveHa; public Dem5() { deHandle ...

  7. c# Delegate and event in ( To continue )( turn )

    This article will discuss some of the more detailed issues of delegation and events , Including some questions you often ask , And event accessors . exception handling . Timeout processing and asynchronous method calls . Why use events instead of delegate variables ? stay C# Delegate and event in in , I put forward two suggestions for ...

  8. C# Some knowledge points : The difference between delegation and event

    stay C# in , Delegation and event are two easily confused knowledge points , This blog records the difference between delegation and event . The difference in definition entrust : A delegate is actually a class , Used to represent a function , It can be understood as C++ Function pointer in . event : The event is a modification ...

  9. C# Delegate and event in

    Objective record Use method as parameter of method Bind method to delegate Better encapsulation Limit type capabilities Example Observer Introduction to design mode Implementation example Observer Design patterns .NET Delegation and events in the framework Why does delegation define ...

Random recommendation

  1. .NET Application Architecture Design — Parametric query design for query service ( Break down the business point , Configure the data query contract separately )

    Read the directory : 1. Background introduction 2. Logical division of business function points ( Such as :A.B.C There are three business sites respectively ) 2.1. Configure mapping relationships , Configure the query contract for the point of business ( structure VS Plug ins facilitate the generation of query contracts ) 2.2. Put the configured mapping policy file in the call ...

  2. page Button/Link The parameter

    In many cases , We need to add a... To a standard page button perhaps yes Link, In the process of clicking, I want to , Some parameters are transferred to another custom page : Here's an example of how it works As shown in the figure below , It's about creating another Obje ...

  3. servers Add server when , You don't see the choice of the operating environment .

    servers Add server when , You don't see the choice of the operating environment . The main reason is tomcat The configuration file in the directory is not in the right format .

  4. CSS Summary of ( Selectors , Pseudo class, etc ...)

    For combinatorial selectors, please refer to :http://www.cnblogs.com/starof/p/4453458.html primary coverage CSS summary CSS and HTML Four ways to combine CSS Style priorities and code specifications CSS ...

  5. Unsupported major.minor version 52.0

    Run the project today , Switch over eclipse, The running program suddenly finds a common class main() Method cannot run , The details of the error report are as follows : Exception in thread "main" java.lang ...

  6. stay go Use in json As the main configuration format

    Recently in use go restructure , In the previous code , What we use ini File , But because of many historical problems , This leads to configuration confusion , Difficult to maintain , Naturally, we need to think about refactoring . Common configuration format There are many common configuration formats , The common ones are ini,json ...

  7. JAVA EE Learning objectives of

    This semester is the second semester of junior year , It's a critical period of study . Set a short-term goal here . Career development goals : My career goal is not computer direction , I'm preparing for the exam . however , As a second-hand major, I plan to , If you fail in the civil service exam , I analyze it according to my personality. I will choose ...

  8. 29. SpringBoot Redis Non comment

    1. Introduce dependencies <parent> <groupId>org.springframework.boot</groupId> <artifactId>spr ...

  9. JS post Submit Form

    js post There are two ways to submit a form ,1:AJAX Submit 2: stay JS You can spell one out of it form, then submit The code for the second approach // This is mainly for password MD5 var email = 'ema ...

  10. NSLog Evolution

    Use the following code to print the line number , Function function , And what to print #if DEBUG #define MBLog(format, ...) NSLog((@"%s--[Line:%d]--" fo ...