C# Tutoriallogin
C# Tutorial
author:php.cn  update time:2022-04-11 14:06:23

C# anonymous methods



We have already mentioned that a delegate is used to refer to a method that has the same label as it. In other words, you use a delegate object to call methods that can be referenced by the delegate.

Anonymous methods (Anonymous methods) Provides a technology for passing code blocks as delegate parameters. Anonymous methods are methods that have no name but only a body.

In anonymous methods you do not need to specify the return type, it is inferred from the return statement within the method body.

Syntax for writing anonymous methods

Anonymous methods are declared by creating a delegate instance using the delegate keyword. For example:

delegate void NumberChanger(int n);
...
NumberChanger nc = delegate(int x)
{
    Console.WriteLine("Anonymous Method: {0}", x);
};

Code block Console.WriteLine("Anonymous Method: {0}", x); is the body of the anonymous method.

A delegate can be called through an anonymous method or a named method, that is, by passing method parameters to the delegate object.

For example:

nc(10);

Example

The following example demonstrates the concept of anonymous methods:

using System;

delegate void NumberChanger(int n);
namespace DelegateAppl
{
    class TestDelegate
    {
        static int num = 10;
        public static void AddNum(int p)
        {
            num += p;
            Console.WriteLine("Named Method: {0}", num);
        }

        public static void MultNum(int q)
        {
            num *= q;
            Console.WriteLine("Named Method: {0}", num);
        }
        public static int getNum()
        {
            return num;
        }

        static void Main(string[] args)
        {
            // 使用匿名方法创建委托实例
            NumberChanger nc = delegate(int x)
            {
               Console.WriteLine("Anonymous Method: {0}", x);
            };
            
            // 使用匿名方法调用委托
            nc(10);

            // 使用命名方法实例化委托
            nc =  new NumberChanger(AddNum);
            
            // 使用命名方法调用委托
            nc(5);

            // 使用另一个命名方法实例化委托
            nc =  new NumberChanger(MultNum);
            
            // 使用命名方法调用委托
            nc(2);
            Console.ReadKey();
        }
    }
}

When the above code is compiled and executed, it will produce the following results:

Anonymous Method: 10
Named Method: 15
Named Method: 30

php.cn