Object-oriented (delegate)

Source: Internet
Author: User

Commissioned

parameterization of the method It is also called an agent to pass the method as a parameter, and the event is a delegate.

Defined at the outermost of the class

Key Words: Delegate

Function Signature: Signature and function remain consistent

When defining a delegate, you define it according to the function.

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

The return type of the method pointed to requires the parameters to be consistent!

2 , defining a delegate variable, pointing to a method

A delegate cannot be instantiated because it is not a class;

First f = new Jiafa (). Jiafa; New delegate variable, point to method, note!! method does not need parentheses!!

The second time you can use +=

public int Jiafa (int a,int b)

{

return a+b;

}

Call:

f (5,3);

Can be understood as a pointer to a function, which function the delegate points to, which function is represented by the delegate

Allows functions to be passed as arguments

Cases:

Defining delegates

public delegate void Suibian (string s);

Class Program

{

static void Main (string[] args)

{

Test T1 = new test ();

Test t2 = new Test ();

DBDA db = Dbda. Duixiang ();

Db.host = "localhost";

Dbda db1 = Dbda. Duixiang ();

Commissioned

Parameterization of the method

Suibian s = China;

s + = America; + = is the binding method = minus a method

Event

Events are a special kind of delegate

Calling a speech method

Speak (s);

Console.WriteLine ();

Console.ReadLine ();

}

Methods of speech function

static void Speak (Suibian yu)

{

Yu ("Zhang San");

if (n = = 0)

//{

America ();

//}

else if (n = = 1)

//{

China ();

//}

else if (n = = 2)

//{

Hanyu ();

//}

}

Voice Pack

public static void America (string s)

{

Console.WriteLine (s+ "Hello");

}

static void China (string s)

{

Console.WriteLine (s+ "Hello");

}

static void Hanyu (string s)

{

Console.WriteLine (s+ "Bjdkaj");

}

}

Object-oriented (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.