C # Delegate Chapter

Source: Internet
Author: User

{
Defines a delegate type, if the passed method has parameters here must be called, because the invocation of the delegate will be used when the
delegate int Adddel (int a, int b);
delegate int AddDel2 (int a, int b);
static void Main (string[] args)
{
#region the ordinary delegate
Calling a static method
Adddel del = new Adddel (ADDSTATICFUNC); Adddel del=addstaticfunc--can write like this.
Console.WriteLine (Del (1, 2));

Invoking instance methods
AddDel2 Del2 = new AddDel2 (new program (). ADDINSTANSFUNC);
Console.WriteLine (Del2 (3, 4));

Console.readkey ();
#endregion

#region Generic Delegate
Func<int, int, int> func =addstaticfunc; -Note that when a delegate specifies a method, it can be specified in the new delegate (the method name) or directly as the current specified
A lambda expression, a lambda statement, an anonymous method can be used wherever a delegate specifies a method.
Func<int, int, int> func = new func<int, int, int> ((A, B) + A + b);----lambda expression
Func<int, int, int> func = new func<int, int, int> (delegate (int a, int b) {return a + B;}); ---anonymous methods
Func<int, int, int> func = (int a, int b) + = {return a + B;};//Note that when you write a lambda expression () {} You can omit the case where there is only one variable or one statement inside it.

Console.WriteLine (Func (1, 3));
Console.readkey ();
#endregion

}
<summary>
Static methods
</summary>
<param name= "a" ></param>
<param name= "B" ></param>
<returns></returns>
static int Addstaticfunc (int a, int b)
{
return a + B;
}
<summary>
Instance method
</summary>
<param name= "a" ></param>
<param name= "B" ></param>
<returns></returns>
public int Addinstansfunc (int a, int b)
{
return a + B;
}
}

C # Delegate Chapter

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.