C# Anonymous Methods
We have already mentioned that delegates are used to reference methods that have the same label as them. In other words, you use a delegate object to call methods that can be referenced by the delegate.
Anonymous methods provide a technique for passing blocks of code as delegate parameters. Anonymous methods are methods that have no name but only a body.
In anonymous methods you don’t need to specify the return type, it is inferred from the return statement inside 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 via an anonymous method or a named method, i.e. 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
The above is [c# tutorial] C# anonymous The content of the method, please pay attention to the PHP Chinese website (www.php.cn) for more related content!