Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

The method of anonymity


May 11, 2021 C#


Table of contents


The anonymous method of C#

As we've already mentioned, delegates are methods that reference the same labels as them. In other words, you can use delegate objects to call methods that can be referenced by delegates.

Anonymous methods provide a technique for passing blocks of code as delegate parameters. Anonymous methods are methods that have no name but principals.

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

Write the syntax for anonymous methods

Anonymous methods are declared by creating delegate instances by 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 by an anonymous method, or by a named method, that is, by passing method parameters to a delegate object.

For example:

nc(10);

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 produces the following results:

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