Книга: C# 2008 Programmer

Anonymous Methods and Lambda Expressions

Anonymous Methods and Lambda Expressions

Beginning with C# 2.0, you can use a feature known as anonymous methods to define a delegate.

An anonymous method is an "inline" statement or expression that can be used as a delegate parameter. To see how it works, take a look at the following example:

class Program {
 delegate void MethodsDelegate(string Message);
 static void Main(string[] args) {
  MethodsDelegate method = Method1;
  //---call the delegated method---
  method("Using delegate.");
  Console.ReadLine();
 }
 static private void Method1(string Message) {
  Console.WriteLine(Message);
 }
}

Instead of defining a separate method and then using a delegate variable to point to it, you can shorten the code using an anonymous method:

class Program {
 delegate void MethodsDelegate(string Message);
 static void Main(string[] args) {
  MethodsDelegate method = delegate(string Message) {
   Console.WriteLine(Message);
  };
  //---call the delegated method---
  method("Using anonymous method.");
  Console.ReadLine();
 }
}

In this expression, the method delegate is an anonymous method:

MethodsDelegate method = delegate(string Message) {
 Console.WriteLine(Message);
};

Anonymous methods eliminate the need to define a separate method when using delegates. This is useful if your delegated method contains a few simple statements and is not used by other code because you reduce the coding overhead in instantiating delegates by not having to create a separate method.

In C# 3.0, anonymous methods can be further shortened using a new feature known as lambda expressions. Lambda expressions are a new feature in .NET 3.5 that provides a more concise, functional syntax for writing anonymous methods.

The preceding code using anonymous methods can be rewritten using a lambda expression:

class Program {
 delegate void MethodsDelegate(string Message);
 static void Main(string[] args) {
  MethodsDelegate method = (Message) => { Console.WriteLine(Message); };
  //---call the delegated method---
  method("Using Lambda Expression.");
  Console.ReadLine();
 }
}

Lambda expressions are discussed in more detail in Chapter 14.

Оглавление книги


Генерация: 1.250. Запросов К БД/Cache: 3 / 1
поделиться
Вверх Вниз