C #2.0 simple explanation of the anonymous method

Source: Internet
Author: User
Anonymous Method

What is an anonymous method ??? I have seen a lot of articles on the Internet. It is very complicated to say something simple and I should simply say something simple .. (Too much nonsense, huh, huh)
So what is an anonymous method ?? Simply put, there is no name ..
Generally, you define a method in a class.
Public void MyMethod ()
{
// A piece of code
}
Such a method called MyMethod () is defined .. This is the method with a name.
So what about the anonymous method?
{
// A piece of code
}
So what is the role of the anonymous method? Let's take a look at the following code.
Class SomeClass
{
// Define a delegate here
Delegate void SomeDelegate ();
Public void InvokeMethod ()
{
// Instantiate a delegate and the delegate directs to the SomeMethod Method
SomeDelegate del = new SomeDelegate (SomeMethod );
Del ();
}
// Delegate Method
Void SomeMethod ()
{
MessageBox. Show ("Hello ");
}
}

The above code is the standard delegate use code in dotnet1.1.

Let's take a look at how Microsoft writes the new anonymous method after it appears?
Class SomeClass
{
// Define a delegate statement like 1.1
Delegate void SomeDelegate ();
Public void InvokeMethod ()
{
// Instantiate the delegate
SomeDelegate del = delegate ()
// Note that there is no name here. Here is a method without a name, which is directly defined after the delegate and will be directly assigned to the delegate.
{
MessageBox. Show ("Hello ");
};
Del ();
}
}

By comparing the above code, we can see that this is just a simplified developer code. In essence, in the process of compiling and translating the code into IL,
The compiler will still give a name for this method without a name. But you don't need to worry about this process...
It is really advanced, and Microsoft said that using the anonymous method will speed up the operation efficiency, and I do not know whether it is true or false. I have never practiced it ..

The following is the usage of Microsoft's MSDN...
C # supports delegate ). The delegate provides operators and methods to add or delete target methods. It can also be widely used in the entire. NET Framework for events, callbacks, asynchronous calls, and multithreading. However, to use a delegate, you sometimes have to create a class or method. In this case, there is no need for multiple targets, and the called code is usually relatively short and simple. In C #2.0, an anonymous method is a new function that allows you to define an anonymous (or unnamed) method called by a delegate.

For example, the following is a general SomeMethod method definition and delegate call:

class SomeClass{delegate void SomeDelegate();public void InvokeMethod(){SomeDelegate del = new SomeDelegate(SomeMethod);del();}void SomeMethod(){MessageBox.Show("Hello");}}

You can use an anonymous method to define and implement this method:

class SomeClass{delegate void SomeDelegate();public void InvokeMethod(){SomeDelegate del = delegate(){MessageBox.Show("Hello");};del();}}

An anonymous method is defined as an in-line method, rather than a member method of any class. In addition, the method attribute cannot be applied to an anonymous method, and the anonymous method cannot define a general type or add a general constraint.

You should pay attention to two important things about anonymous methods: Reload use of delegated reserved keywords and delegate assignment. Later, you will see how the compiler implements an anonymous method. By viewing the code, you will have a clear understanding of the types of delegates that the compiler must use for reasoning, instantiate a new delegate object of the reasoning type, encapsulate the new delegate into an anonymous method, and assign it to the delegate used in the anonymous method definition (del in the previous example ).

The anonymous method can be used wherever the delegate type is needed. You can pass an anonymous method to any method, as long as the method accepts the appropriate delegate type as the parameter:

class SomeClass{delegate void SomeDelegate();public void SomeMethod(){InvokeDelegate(delegate(){MessageBox.Show("Hello");});}void InvokeDelegate(SomeDelegate del){del();}}

To pass an anonymous method to a method that accepts the abstract Delegate parameter, for example:

void InvokeDelegate(Delegate del);

First, you must forcibly convert the anonymous method to a specific delegate type.

The following is a specific and practical example of Passing anonymous methods as parameters. It starts a new thread without explicitly defining ThreadStart delegation or thread methods:

public class MyClass{public void LauchThread(){Thread workerThread = new Thread(delegate(){MessageBox.Show("Hello");});workerThread.Start();}}

In the previous example, the anonymous method is used as a thread method, which causes the message box to be displayed in the new thread.

Back to Top

PASS Parameters to anonymous methods

When defining an anonymous method with parameters, you should define the parameter type and name after the delegate keyword, just as if it is a conventional method. The method signature must match the definition of the delegate it assigns. When a delegate is called, the parameter value can be passed, which is exactly the same as that of a normal delegate call:

class SomeClass{delegate void SomeDelegate(string str);public void InvokeMethod(){SomeDelegate del = delegate(string str){MessageBox.Show(str);};del("Hello");}}

If the anonymous method does not have a parameter, you can use an empty pair of parentheses after the delegate Keyword:

class SomeClass{delegate void SomeDelegate();public void InvokeMethod(){SomeDelegate del = delegate(){MessageBox.Show("Hello");};del();}}

However, if you ignore the delegate keyword along with the empty parentheses, you define a special anonymous method that can be assigned to any delegate with any signature:

class SomeClass{delegate void SomeDelegate(string str);public void InvokeMethod(){SomeDelegate del = delegate{MessageBox.Show("Hello");};del("Parameter is ignored");}}

Obviously, if the anonymous method does not depend on any parameter and you want to use this method code that is irrelevant to the delegate signature, you can only use this syntax. Note: When calling a delegate, you still need to provide the parameter because the compiler generates an anonymous parameter for the anonymous method inferred from the delegate signature, as if you have written the following code (in the C # pseudo code:

SomeDelegate del = delegate(string){MessageBox.Show("Hello");};

In addition, the anonymous method without the parameter list cannot be used together with the delegate that points out the parameter.

The anonymous method can use any class member variable, and it can also use any local variable defined within its scope of inclusion, just as if it was its own local variable. Figure 7 shows this. Once you know how to pass parameters for an anonymous method, you can easily define anonymous event processing, as shown in figure 8.

Because the + = Operator only connects the internal call list of one delegate to the internal call list of another delegate, you can use + = to add an anonymous method. Note: In case of anonymous event processing, you cannot use the-= Operator to delete the event processing method, unless you add the anonymous method as the handler, you can first store the anonymous method as a delegate, and then register the delegate through the event. In this case, you can use the-= operator with the same delegate to cancel registration of anonymous methods as the handler.

Back to Top

Anonymous method implementation

The code generated by the compiler for an anonymous method depends largely on the type of parameters or variables used by the anonymous method. For example, does an anonymous method use the local variables (also called external variables) that contain the method, or the class member variables and method parameters? In either case, the compiler generates different MSIL. If the anonymous method does not use external variables (that is, it only uses its own parameters or class members), the compiler will add a private Method to the class, to assign a unique name to the method. The method name is in the following format:

<return type> __AnonymousMethod$<random unique number>(<params>)

Like other compiler members, this will change, and is most likely to change before the final version is released. The method signature will be the signature of the delegate it assigns.

The compiler simply converts anonymous method definitions and assignments to standard instances of the reasoning delegate type to wrap the private method generated by the machine:

SomeDelegate del = new SomeDelegate(__AnonymousMethod$00000000);

It is very interesting that the private method generated by the machine is not displayed in intelliisense, nor can it be explicitly called, because the dollar sign in its name is an invalid identifier for the C # method (but it is a valid MSIL tag ).

It is more difficult to use external variables in an anonymous method. In this case, the compiler adds a private nested class with a unique name in the following format:

__LocalsDisplayClass$<random unique number>

A nested class has a reference to the containing class named <this>, which is a valid MSIL member variable name. The nested class contains the public member variables corresponding to each external variable used by the anonymous method. The compiler adds a public method with a unique name to the nested class definition. The format is as follows:

<return type> __AnonymousMethod$<random unique number>(<params>)

The method signature will be the signature of the assigned delegate. The compiler uses code to replace anonymous definitions. This Code creates an instance of a nested class and assigns a value from an external variable to the member variable of the instance. Finally, the compiler creates a new delegate object to wrap the public methods of nested class instances, and then calls the delegate to call this method. Figure 9 uses the C # pseudocode to show the code generated by the compiler for the anonymous method defined in Figure 7.

Back to Top

General anonymous method

Anonymous methods can use common parameter types, just like other methods. It can use a general type defined within the scope of the class, for example:

class SomeClass<T>{delegate void SomeDelegate(T t);public void InvokeMethod(T t){SomeDelegate del = delegate(T item){...}del(t);}}

Because the delegate can define general parameters, the anonymous method can use the general type defined at the delegate layer. You can specify the type used for the method signature. In this case, the method signature must match the specific type of the delegate assigned to it:

class SomeClass{delegate void SomeDelegate<T>(T t);public void InvokeMethod(){SomeDelegate<int> del = delegate(int number){MessageBox.Show(number.ToString());};del(3);}}
Back to Top

Anonymous method example

Although the use of anonymous methods may seem like an alternative programming technique at first glance, I find it quite useful, because when one delegate is sufficient, you do not need to create a simple method. Figure 10 shows a practical example of a useful anonymous method-the SafeLabel Windows form control.

Windows Forms depend on basic Win32 messages. Therefore, it inherits the typical Windows programming requirements: only the thread that creates a window can process its messages. In. NET Framework 2.0, a thread that calls an error will always trigger an exception in the Windows form. Therefore, when calling a form or control in another thread, you must mail the call to the correct thread. Windows Forms have built-in support for getting rid of this dilemma by using the Control base class to implement the ISynchronizeInvoke interface, which is defined as follows:

public interface ISynchronizeInvoke{bool InvokeRequired {get;}IAsyncResult BeginInvoke(Delegate method,object[] args);object EndInvoke(IAsyncResult result);object Invoke(Delegate method,object[] args);}

The Invoke method accepts the delegate for the method in the corresponding thread, and mails the call from the thread being called to this thread. Because you may not always know whether you are actually running in the correct thread, you can use the InvokeRequired attribute to query and determine whether to call the Invoke method. The problem is that using ISynchronizeInvoke will greatly increase the complexity of the programming model. Therefore, a better method is to encapsulate interactions with ISynchronizeInvoke interfaces in controls or forms, they automatically use ISynchronizeInvoke as needed.

For example, to replace the Label control that exposes the Text property, you can define the SafeLabel control derived from the Label, as shown in 10. SafeLabel overrides the Text attribute of its base class. In its get and set, it checks whether the Invoke is required. If so, it needs to use a delegate to access this attribute. This implementation only calls the implementation of the basic class attribute, but is on the correct thread. Because SafeLabel only defines these methods, they can be called by delegation. They are good candidates for anonymous methods. SafeLabel passes such a delegate to encapsulate the anonymous method as the security implementation of its Text attribute into the Invoke method.

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.