Delegate lambda expressions for easy understanding, lambda expressions
The method cannot be the same as the variable when passing the parameter. C # defines the delegate so that the method can be passed as the variable. In order to be simple and pass the anonymous method, it is unnecessary to declare the method; lambda expressions are more intuitive than anonymous methods.
Public delegate int delegateArithmetic (int a, int B );
// The delegate is used as a parameter and the method is passed to the Delegate
Public int result (int x, int y, delegateArithmetic delAri)
{
Return delAri (x, y );
}
Public int Sum (int m, int n)
{
Return m + n;
}
Private void button2_Click (object sender, EventArgs e)
{
TextBox2.Text = "";
// The delegate is used as a parameter and the method is passed to the Delegate
Var r1 = result (8, 5, Sum );
TextBox2.Text = textBox2.Text + "pass the method to delegate. The result of adding the two numbers is:" + r1.ToString () + "\ r \ n ";
// The delegate is used as a parameter, and the anonymous method is passed to the Delegate
Var r2 = result (8, 5, delegate (int a, int B) {return a-B ;});
TextBox2.Text = textBox2.Text + "the anonymous method is passed to delegate. The result of two Subtraction is:" + r2.ToString () + "\ r \ n ";
// The delegate is used as a parameter, and the lambda expression is passed to the Delegate
Var r3 = result (8, 5, (x, y) => {return x * y ;});
TextBox2.Text = textBox2.Text + "the lambda expression is passed to delegate. The result is multiplied by two numbers:" + r3.ToString () + "\ r \ n ";
// Delegate as a parameter. The simple lambda expression is passed to the delegate.
Var r4 = result (8, 5, (x, y) => x * y );
TextBox2.Text = textBox2.Text + "the simple lambda expression is passed to delegate. The result is multiplied by two numbers:" + r4.ToString () + "\ r \ n ";
}
Lambda expressions are simplified anonymous methods. When the C # compiler compiles the lambda expressions into anonymous methods.