Csharp/C Sharp/Language Basics/delegate anonymous

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Anonymous methods can be assigned a signature

<source lang="csharp"> using System; using System.Threading;

public delegate int DelegateClass(out int param); public class Starter {

   public static void Main() {
       int var;
       DelegateClass del = delegate(out int inner) {
           inner = 12;
           Console.WriteLine("Running anonymous method");
           return inner;
       };
       del(out var);
       Console.WriteLine("Var is {0}", var);
   }

}

</source>


Anonymous methods can be assigned a signature, which is appended to the delegate keyword.

<source lang="csharp"> using System; using System.Threading;

public delegate int DelegateClass(out int param); public class Starter {

   public static void Main() {
       int var;
       DelegateClass del = delegate(out int inner) {
           inner = 12;
           Console.WriteLine("Running anonymous method");
           return inner;
       };
       del(out var);
       Console.WriteLine("Var is {0}", var);
   }

}

</source>


Anonymous methods can refer to local variables of the containing function and class members within the scope of the method definition

<source lang="csharp"> using System; public delegate void DelegateClass(out int arg); public class Starter {

   public static void Main() {
       DelegateClass del = MethodA();
       int var;
       del(out var);
       Console.WriteLine(var);
   }
   public static DelegateClass MethodA() {
       int local = 0;
       return delegate(out int arg) {
           arg = ++local;
       };
   }

}

</source>


Define an anonymous method with the delegate keyword.

<source lang="csharp"> using System; using System.Threading; public delegate void DelegateClass(); public class Starter {

   public static void Main() {
       DelegateClass del = delegate {
           Console.WriteLine("Running anonymous method");
       };
       del();
   }

}

</source>


Local variables used in an anonymous method are called outer variables.

<source lang="csharp"> using System; public delegate void DelegateClass(out int arg); public class Starter {

   public static void Main() {
       DelegateClass del = MethodA();
       int var;
       del(out var);
       Console.WriteLine(var);
   }
   public static DelegateClass MethodA() {
       int local = 0;
       return delegate(out int arg) {
           arg = ++local;
       };
   }

}

</source>


two delegates and anonymous methods

<source lang="csharp"> using System;

public delegate void ADelegate(int param); public delegate int BDelegate(int param1, int param2); public class Starter {

   public static void Main() {
       ADelegate del = delegate(int param) {
           param = 5;
       };
   }
   public int MethodA() {
       BDelegate del = delegate(int param1, int param2) {
           return 0;
       };
       return 0;
   }

}

</source>