Anonymous delegates and lambda expressions that use the action, func,eventhandler,params keyword-decorated parameters
In. NET, we often use the delegate, the role of the delegate needless to say, before. NET 2.0, before we use the delegate, we have to customize a delegate type and then use this custom delegate type to define a delegate field or variable.. NET 2.0 brings US action, Func two generic delegates,. NET3.0 gives us a lambda, which makes the definition and use of the delegate simpler. The delegate in the following example uses a lambda expression.
A generic delegate for the action series
The delegate for the action series defines a delegate that has no return value (the return value is void). It has several versions including no input parameters, 1 input parameters, 2 input parameters, 3 input parameters, 4 input parameters in total 5 versions of the prototypes are as follows:
1. No input parameter returns a delegate with a value of void.
The action delegate encapsulates a method that takes no arguments and does not return a value.
You can use this delegate as a parameter to pass a method that performs an action without explicitly declaring a custom delegate to encapsulate this method. The encapsulated method must correspond to the method signature defined by this delegate. This means that the method must not have parameters and return values. Cases:
Using System;
Using System.Windows.Forms;
public class Name
{
private string instancename;
public actionshowname;
Public Show ()
{
If (showname!= null)
showname ();
}
Public Name (string name)
{
this.instancename = name;
Public
void Displaytoconsole ()
{
Console.WriteLine (this.instancename);
Public
void Displaytowindow ()
{
MessageBox.Show (this.instancename);
}
public
class Actionstudy
{public
static void Main ()
{
Name testname = new Name (" Koani ");
Testname.showname = () => Testname.displaytowindow ();
Testname.show ();
}
}