Summary of naming and anonymous methods

Source: Internet
Author: User
Summary of naming and anonymous methods Naming Method

The delegate can be associated with the naming method. When a delegate is instantiated using a named method, this method is passed as a parameter, for example:
// Declare a delegate:
Delegate void Del (int x); // defines a delegate (note the following signature)
// Define a named method:
Void DoWork (int k ){/*...*/}
// Instantiate the delegate using the method as a parameter:
Del d = obj. DoWork; // use the naming method named parameter to delegate Initialization
This is called the naming method. The delegate constructed using the naming method can encapsulate static methods or instance methods. In previous C # versions, naming is the only way to instantiate a delegate. However, C #2.0 allows you to instantiate a delegate when the system overhead for creating a new method is unnecessary, that is, when you create a delegate object, immediately specify the code block that the delegate object will process when it is called. These are called anonymous methods.
The method passed as the delegate parameter must have the same signature as the delegate declaration. The delegated instance can encapsulate static or instance methods.
Although the delegate can use the out parameter, it is not recommended to use it in multi-channel broadcast event delegation because it is unable to determine which delegate to call.
Example 1
The following is a simple example of declaring and using delegation. Note that the delegated Del and associated method MultiplyNumbers have the same signature
// Declare a delegate
Delegate void Del (int I, double j); // signature indicates the return type, number of parameters, and parameter type of the delegate type.
Class MathClass
{
Static void Main ()
{
MathClass m = new MathClass (); // m: A MathClass object
// Delegate instantiation using "MultiplyNumbers"
Del d = m. MultiplyNumbers; // The method used to encapsulate MultiplyNumbers by delegation instantiation
// Invoke the delegate object.
System. Console. WriteLine ("Invoking the delegate using 'multiplynumbers ':");
For (int I = 1; I <= 5; I ++)
{
D (I, 2); // call

}

}

// Declare the associated method. defines a method associated with the preceding delegate

Void MultiplyNumbers (int m, double n)
{
System. Console. Write (m * n + "");
}

}
Output
Invoking the delegate using 'multiplynumbers ':
2 4 6 8 10
Example 2
In the following example, a delegate is mapped to both the static method and the instance method, and specific information is returned respectively.
// Declare a delegate
Delegate void Del (); private non-return value-less parameter delegate type
Class SampleClass
{
// Declare two methods in this class

Public void InstanceMethod ()
{
System. Console. WriteLine ("A message from the instance method .");
}

Static public void StaticMethod ()
{
System. Console. WriteLine ("A message from the static method .");
}

}
Class TestSampleClass
{

Static void Main ()
{
SampleClass SC = new SampleClass ();

// Map the delegate to the instance method:
Del d = SC. InstanceMethod;
D ();
// Map to the static method:
D = SampleClass. StaticMethod;
D ();
}

}
Output
A message from the instance method.
A message from the static method.
Finally understand

Anonymous Method
In C # versions earlier than 2.0, the only way to declare a delegate is to use the naming method. C #2.0 introduces the anonymous method.
To pass a code block as a delegate parameter, creating an anonymous method is the only method. For example:
// Create a handler for a click event
Button1.Click + = delegate (System. Object o, System. EventArgs e)
{System. Windows. Forms. MessageBox. Show ("Click! ");};
Or
C #
// Create a delegate instance
Delegate void Del (int x );

// Instantiate the delegate using an anonymous method
Del d = delegate (int k ){/*...*/};
If the anonymous method is used, you do not need to create a separate method. Therefore, the coding system overhead required for instantiating the delegate is reduced.
For example, if the system overhead required to create a method is unnecessary, it is very useful to specify a code block at the delegate position. Starting a new thread is a good example. Without creating more methods for the delegate, the thread class can create a thread and contain the code executed by the thread.
Void StartThread ()
{
System. Threading. Thread t1 = new System. Threading. Thread (// use the anonymous method
Delegate (){
System. Console. Write ("Hello ,");
System. Console. WriteLine ("World! ")});
T1.Start ();
}
The parameter range of the anonymous method is anonymous-method-block.

It is wrong to use Jump statements (such as goto, break, or continue) in the anonymous method block outside the block. Using jump statements (such as goto, break, or continue) outside the anonymous method block of the target block is also incorrect.

If the range of local variables and parameters includes anonymous method declaration, the local variables and parameters are called external variables of the anonymous method or capture variables. For example, n in the following code segment is an external variable:
Int n = 0;
Del d = delegate () {System. Console. WriteLine ("Copy #:{ 0}", ++ n );};
Unlike local variables, the life cycle of external variables continues until the delegates that reference the anonymous method meet the garbage collection conditions. References to n are captured when the delegate is created.
The anonymous method cannot access the ref or out parameters in the external range.
You cannot access any Insecure code in anonymous-method-block.
The following example demonstrates two ways to instantiate a delegate:
Associate a delegate with an anonymous method.
Associate a delegate with a naming method (DoWork.
Both methods will display a message when calling the delegate.
// Declare a delegate
Delegate void Printer (string s );
Class TestClass
{

Static void Main ()
{
// Instatiate the delegate type using an anonymous method: // use the anonymous method
Printer p = delegate (string j) {System. Console. WriteLine (j );};

// Results from the anonymous delegate call:
P ("The delegate using the anonymous method is called .");

// The delegate instantiation using a named method "DoWork ":
P = new Printer (TestClass. DoWork); // use the naming method to instantiate the delegate object p

// Results from the old style delegate call:
P ("The delegate using the named method is called."); // call p (naming method)
}

// The method associated with the named delegate:
Static void DoWork (string k)
{
System. Console. WriteLine (k );
}

}

Output
The delegate using the anonymous method is called.
The delegate using the named method is called.

When an anonymous method is used in a class, CLR automatically generates an EventHandler with the same signature and a method to process it. Therefore, the anonymous method only reduces the amount of encoding.
The following sample code is for your criticism:
C # Source Code:
... // Reference the namespace
Namespace HolyHouse
{
Class Program
{

Static void main (string [] args) // main function (method)
{
Person p = new Person ("Holy"); // initialize (instantiate) Person Class Object P
P. Say + = delegate () {Console. WriteLine ("Yeah. Where is my method? ") ;}; // Mount an anonymous method on the P event Say (call the console output)
Console. WriteLine (p. ToString (); // call the ToString () method of P.
Console. Read (); // enter any value to end

}

}
Class Person
{

Public event EventHandler Say; // method of declaring an event (Special Delegate)
Public string Name;
Public Person (string name)
{
Name = name;
}

Protected virtual void OnSay (EventArgs e) // Store event data in the e object. In this example, e is a NULL data set (no event data)
{

If (Say! = Null) // determine whether the event is attached to any type of method
{
Say (this, e); // call the event. If the event is attached to a method, pass e to the method.
}

}

Public override string ToString () // rewrite ToString () method
{
OnSay (EventArgs. Empty); // call method OnSay (); EventArgs. Empty indicates that the event data is Empty.
Return string. Format ("My name is {0}, thank you.", Name );
}

}
}
Output:
Yeah. Where is my method?
My name is Holy, thank you.
When viewing the IL code, you can see that the Program class contains an EventHandler named <> 9 _ CachedAnonymousMethodDelegate1 and an EventHandler named The method of B _ 0 that matches the EventHandler signature.
Unfinished ......

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.