C # Delegate

Source: Internet
Author: User

Commissioned
    • If we want to pass the method as a parameter, we use the delegate, which simply means that the delegate is a type, which can assign a reference to a method.
Declaring a delegate
    • Use a class in C # in two stages, first defining the class, telling the editor what fields and methods The class consists of, and then instantiating the object using this class. When we use the delegate, we need to go through both phases, first defining the delegate, telling the editor that we can point to those types of methods, and then create an instance of the delegate.

    • Here's how to define a delegate:

      • delegate void IntMethodInvoker(int x);

      • Define a delegate: IntMethodInvoker what type of method can this delegate point to?

      • This method takes a parameter of a int type, and the return value of the method is defined by defining void a delegate to define the parameters and return values of the method, using the keyword delegate definition.

    • To define a case:

      • delegate double TwoLongOp(long frist, long second);
      • delegate string GetAString();
Delegate use
Private delegate string getastring (); static void Main () {int x = 40; getAString Firststringmethod = new getAString (x.tostring); Console.WriteLine (Firststringmethod ());}

  

    • Here we first use GetAString a delegate to declare a type called fristStringMethod , and then use new it to initialize it to refer to x the ToString method in, so that firstStringMethod is equivalent x.ToString to the firstStringMethod() way we execute the method is equivalent to x.ToString()

    • There are two ways to call a method by using the delegate sample:

      • fristStringMethod();
      • firstStringMethod.Invoke();
Assignment of a delegate
    • GetAString firstStringMethod = new GetAString(x.ToString);
    • You GetAString firstStringMethod = x.ToString; just need to give the method name to a delegate's constructor.
    • You can also give the method name directly to the instance of the delegate
Simple Delegate Example
    • Define a class mathsoperations there are two static methods that use delegates to invoke the method
Class Mathoperations{public static double Multiplybytwo (double value) {return value*2;} public static double Square (double value) {return value*value;}} Delegate double Doubleop (double x), static void Main () {doubleop[] operations={mathoperations.multiplybytwo, Mathoperations.square};for (int i =0;i<operations. length;i++) {Console.WriteLine ("Using Operations" +i); Processanddisplaynumber (operations[i],2.0);}} static void Processanddisplaynumber (Doubleop action,double value) {Double res = action (value); Console.WriteLine ("Value:" +value+ "Result:" +res);}

  

Action delegate and Func delegate
    • In addition to our own defined delegates, the system also provides us with a built-in delegate type.
    • ActionAndFunc
    • ActionA delegate references a void method of a return type, which T represents a method parameter
    • First look at Action what the delegate has
      • Action
      • Action<in t>
      • Action<in T1,in t2>
      • Action<in t1,in T2 .... int16>
    • FuncRefers to a method with a return value that can pass 0 or more to 16 parameter types, and a return type
      • Func<out tresult>
      • Func<in T,out tresult>
      • Func<int t1,int2,,,,,, in T16,out tresult>
Case 1
    • delegate double DoubleOp(double x);How to use Func representations

    • Func<double,double>

Case 2-Sorting int types
    • Sort the collection, bubble sort
BOOL swapped = true;do{swapped = false;for (int i =0;i<sortarray.length-1;i++) {if (sortarray[i]>sortarray[i+1]) { int temp= sortarray[i];sortarray[i]=sortarray[i+1];sortarray[i+1]=temp;swapped = True;}}} while (swapped);

  

    • The bubble sort here only applies to the int type, if we want to extend it so that it can sort any object.
Case 2-Employee class
Class Employee{public employ (string Name,decimal salary) {this. Name = Name;this. Salary = Salary;} public string name{get;private set;} public decimal salary{get;private set;} public static bool Comparesalary (Employee e1,employee E2) {return e1.salary>e2.salary;}}

  

Case 2-General sorting method
public static void Sort<t> (list<t> sortarray,func<t,t,bool> comparision) {bool swapped = true;do{ swapped = false;for (int i=0;i<sortarray.count-1;i++) {if (comparision (Sortarray[i+1],sortarray[i])) {T temp = sortarray[i];sortarray[i]=sortarray[i+1];sortarray[i+1]=temp;swapped = True;}}} while (swapped);}

  

Case 2-Sort the employee class
static void Main () {employee[] employees = {New Employee ("Bunny", 20000), new employee ("Bunny", 10000), new employee ("Bunny ", 25000), new employee (" Bunny ", 100000), New employee (" Bunny ", 23000), New employee (" Bunny ", 50000),}; Sort (employees,employee.comparesalary);//Output}

  

Multicast delegation
    • The delegate used earlier contains only a call to a method, but a delegate can also contain multiple methods, a delegate called a multicast delegate. Multiple methods can be called sequentially using the multicast delegate, and the multicast delegate can only get the result of the last method called, which we typically declare as the return type of the multicast delegate void .

      • Action action1 = Test1;
      • action2+=Test2;
      • action2-=Test1;
    • The multicast delegate contains a collection of delegate calls-by-call, and if one of the methods invoked by the delegate throws an exception, the entire iteration stops.

    • To obtain a delegate for all methods in a multicast delegate:

Action a1 = method1;a1+=method2;delegate[] delegates=a1. Getinvocationlist (); foreach (delegate d in delegates) {//d ();d. DynamicInvoke (null);} Traverse all the delegates in the multicast delegate, and then call them separately

  

Anonymous methods
    • So far, the use of delegates has been to define a method and then give the method to the instance of the delegate. But there is another way to use a delegate, not to define a method, but to use an anonymous method (the method has no name).
Func<int,int,int> plus = delegate (int a,int b) {int temp = A+b;return temp;}; int res = plus (34,34); Console.WriteLine (RES);

  

    • This is the equivalent of directly writing the method to be referenced directly behind, the advantage is to reduce the code to write, reduce the complexity of the code
Lambda expression-Represents the definition of a method
    • Starting with c#3.0, you can use a lambda expression instead of an anonymous method. A lambda expression can be used wherever there is a delegate parameter type. Just the example can be modified to
  Func<int,int,int> plus = (A, b) =>{int temp= A+b;return temp;};  int res = plus (34,34);  Console.WriteLine (RES);

  

    • The lambda operator "= =" is listed on the left of the required parameters, if it is a parameter can be directly written a=> (parameter name itself), if more than one parameter is enclosed in parentheses, between the arguments, the interval
Multi-line statements
    • If the lambda expression has only one statement, no curly braces and return statements are required within the method, and the compiler automatically adds a return statement
func<double,double> Square = x=>x*x;//Add curly braces, return statements and semicolons are perfectly legal func<double,double> square = x=>{ return x*x;}

  

    • If more than one statement is required in the implementation code of a lambda expression, you must add curly braces and a return statement.
Variables outside the lambda expression
    • A lambda expression provides access to variables outside the lambda expression block. This is a very good feature, but it can be very dangerous if not used correctly. Example:
int somval = 5; func<int,int> f = x=>x+somval; Console.WriteLine (f (3));//8somval = 7; Console.WriteLine (f (3));//10

  

    • The result of this method is not only controlled by the parameter, but also controlled by somval variable, the result is not controllable, it is easy to appear programming problem, use caution.
Event
    • Event is based on a delegate and provides a publish/subscribe mechanism for the delegate, and we can say that the event is a delegate with a special signature. What is an event? An event is a special signature delegate that a class or object notifies other classes or objects of what is happening. The declaration of the event public event delegate type events name; An event is declared using the event keyword, and his return class value is a delegate type. Usually the name of the event, named +event as his name, in the code as far as possible to use canonical naming, increase the readability of the code.
    • To make it easier to understand the event, we still use an example from the previous animal to illustrate that there are three animals, the cat (named Tom), and two mice (Jerry and Jack), when the cat barks, trigger the event (Catshout), and then two mice start to flee (Mouserun). The next step is to implement it in code. (Design mode-viewer mode)
Cat class and Mouse class
      Class Cat {string catname;          String Catcolor {get; set;}              Public Cat (string name, string color) {this.catname = name;         Catcolor = color; } public void Catshout () {Console.WriteLine (catcolor+ "The Cat" +catname+ "came over, Meow! Meow! Meow!             \ n "); When the cat barks when the event is triggered//when the cat barks, if there is an enlistment event in Catshoutevent, then the event is executed if (catshoutevent! = null) Catshoutev         ENT ();         } public delegate void Catshouteventhandler ();     public event Catshouteventhandler Catshoutevent;         } class Mouse {string mousename;         String Mousecolor {get; set;}             Public Mouse (string name, string color) {this.mousename = name;         This.mousecolor = color; } public void Mouserun () {Console.WriteLine (Mousecolor + "Mouse" + Mousename + "said: \" The old cat is coming, run! \ "\ n i run!! \ n I'm running!! I'm speeding up and running!!!         \ n "); }     }

  

Run code results
  Console.WriteLine ("[Scene description]: A Yuemingxingxi midnight, two mice are stealing oil to eat \ \");              Mouse Jerry = new Mouse ("Jerry", "White");              Mouse jack = new Mouse ("Jack", "Yellow");                            Console.WriteLine ("[Scene description]: a black cat crept up and came over \");              Cat Tom = new Cat ("Tom", "Black");              Console.WriteLine ("[Scene description]: In order to safely steal oil, registered a cat-called event \ n");             Tom.catshoutevent + = new Cat.catshouteventhandler (jerry.mouserun);             Tom.catshoutevent + = new Cat.catshouteventhandler (jack.mouserun);             Console.WriteLine ("[Scene description]: cat called three \ n");             Tom.catshout ();             Console.readkey ();

  

The relationship and difference between events and delegates
    • An event is a special delegate, or a restricted delegate, that is a special application that only imposes +=,-= operators. They are essentially a thing.

    • event ActionHandler Tick;Compile to create a private delegate example, and apply the Add, remove method on it.

    • The event only allows operation with the Add, remove method, which causes it not to be triggered directly outside of the class, but only at the right time within the class. The delegate can be triggered externally, but not in this way.

    • In use, delegates are commonly used to express callbacks, and events express outgoing interfaces.

    • Delegates and events support static methods and member methods, delegate (void * pthis, f_ptr), when a static rebate method is supported, pthis NULL. When the member method is supported, Pthis passes the notified object.

    • The three important fields in the delegate object are pthis, F_ptr, Pnext, which is the notification object reference, the function pointer/address, and the next delegate node of the list of delegates.

 

C # Delegate

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.