1.61. C# anonymous method

发布时间 : 2025-10-25 13:34:35 UTC      

Page Views: 10 views

We have already mentioned that delegates are used to reference methods that have the same label as them. In other words, you can use a delegate object to call a method that can be referenced by a delegate.

Anonymous methods provide a technique for passing code blocks as delegate parameters. An anonymous method is a method that has no name but only a principal.

You do not need to specify a return type in an anonymous method, it is derived from the return statement inferred.

1.61.1. Write the syntax for anonymous methods #

Anonymous methods are done by using the delegate keyword to create a delegate instance to declare. 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 bodyof an anonymous method.

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

Note: the body of an anonymous method needs a ; .

For example:

nc(10); 

1.61.2. Example #

The following example demonstrates the concept of anonymous methods:

Example #

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); } static void Main(string[] args) { // Creating a delegate instance using anonymous methods NumberChanger nc = delegate(int x) { Console.WriteLine("Anonymous Method: {0}", x); }; // Using anonymous methods to call delegates nc(10); // Instantiating delegates using naming methods nc = new NumberChanger(AddNum); // Calling delegates using named methods nc(5); // Instantiating a delegate using another naming method nc = new NumberChanger(MultNum); // Calling delegates using named methods 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 
《地理信息系统原理、技术与方法》  97

最近几年来,地理信息系统无论是在理论上还是应用上都处在一个飞速发展的阶段。 GIS被应用于多个领域的建模和决策支持,如城市管理、区划、环境整治等等,地理信息成为信息时代重要的组成部分之一; “数字地球”概念的提出,更进一步推动了作为其技术支撑的GIS的发展。 与此同时,一些学者致力于相关的理论研究,如空间感知、空间数据误差、空间关系的形式化等等。 这恰好说明了地理信息系统作为应用技术和学科的两个方面,并且这两个方面构成了相互促进的发展过程。