C # commissioned study notes

  Use entrusted mainly to solve not know when such events might trigger being used, for example, you opened a restaurant, cooking meals, money, etc., also need to answer the front desk phone call from time to time, this time you We can put this work to answer the phone will be the son to do this thing. This process is called trust. Son take calls can tell you also can not tell you, then see how this type of commission

An ordinary delegate (for example, we want to perform an addition operation a number of two)

Step 1: Define commission (to answer the phone this thing)

public delegate int AddDel(int a,int b);

The method (as defined in a son will answer the phone) to write real additions performed: Step 2

public int FuncAdd(int a,int b)

{

return a+b;

}

Step 3: The method to bind to delegate, a delegate can bind multiple methods, as long as the parameters to meet the requirements, this is what we call a multicast delegate (son answered the phone told this matter)

AddDel myadddel = new AddDel(FancAdd);

Step 4: Start (son began phones, etc.)

myadddel (3, 4); or myadddel.Invoke (3,4);

Second, generic delegate

  In fact, the system has built two defined commission, we can omit step 1 of the general commission

Both systems is entrusted Func <T> and Action <T> is the difference between T Func parameter list, the last one is the return value of type int, and Active no return value.

 1.Func commission

  For example, adding two numbers we use Func wrote as follows:

#region anonymous delegates processing result is returned Func
Func <int, int, int> anonymous delegates I =
the delegate (int A, int B)
{
return A + B;
};
#endregion

   2.Action commission

    If we do not need to return the results of the implementation of a commission to make use Action For instance, we say hellworld

Active #region anonymous delegates do not return the results
Action <string> anonymous delegates I = 2
the delegate (String S)
{
Console.WriteLine (S);
};
my anonymous delegates 2.Invoke ( "hellworld");

#endregion

3. Using a lambda expression to simplify the wording commission

Func <int, int, int> I delegate lambda expression =
(int A, B int) => A + B;

 Action <string> delegate my lambda expression 2 =

(s)=>console.writeline(s);

 

Guess you like

Origin www.cnblogs.com/arcticfish/p/12296082.html
Recommended