Csharp/C Sharp/Language Basics/delegate anonymous
Содержание
- 1 Anonymous methods can be assigned a signature
- 2 Anonymous methods can be assigned a signature, which is appended to the delegate keyword.
- 3 Anonymous methods can refer to local variables of the containing function and class members within the scope of the method definition
- 4 Define an anonymous method with the delegate keyword.
- 5 Local variables used in an anonymous method are called outer variables.
- 6 two delegates and anonymous methods
Anonymous methods can be assigned a signature
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);
}
}
Anonymous methods can be assigned a signature, which is appended to the delegate keyword.
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);
}
}
Anonymous methods can refer to local variables of the containing function and class members within the scope of the method definition
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;
};
}
}
Define an anonymous method with the delegate keyword.
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();
}
}
Local variables used in an anonymous method are called outer variables.
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;
};
}
}
two delegates and anonymous methods
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;
}
}