Original link: http://www.xuebuyuan.com/456117.html
Named Method delegate
Class Mydelegatetest
{
//step 1, declaring delegate object public
delegate void MyDelegate (string name);
This is the method we want to pass, and it has the same parameter and return value type as MyDelegate public
static void Mydelegatemethod (string name)
{
Console.WriteLine ("Hello,{0}", name);
}
public static void Main ()
{
//step 2, create delegate object
mydelegate md = new MyDelegate ( Mydelegatetest.mydelegatemethod);
Step 3, call Delegate
MD ("Michael");
Console.ReadLine ();
}
Anonymous method Delegate
Class Anonymousdelegate
{
private delegate void MyDelegate (string name);
public static void Main ()
{
MyDelegate mydelegate = Delegate (string name)
{
Console.WriteLine (name);
};
MyDelegate ("Michael");
Console.ReadLine ();
}
lambda expression
Lambda expressions are a new syntax for c#3.0, which provides a more concise, functional syntax for writing anonymous methods.
Class Lambdatest
{
private delegate void MyDelegate (string name);
public static void Main ()
{
//anonymous delegate
mydelegate mydelegate = (name) => {Console.WriteLine (name);
//Call Delegate
mydelegate ("Michael");
Console.ReadLine ();
}
Using lambda expressions is simpler and less concise. Actually, the compiler did a lot of things for us. MyDelegate mydelegate = (name) => {Console.WriteLine (name); The compiler will generate a private static method for us at compile time. You can see through the ILDASM.