using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DelegateTest
{
public class test
{
static void Main(string[] args)
{
Class1 c = new Class1();
//用new操作把委托与一个方法关联
SayHello sh = new SayHello(c.SayHelloMethod);
Console.WriteLine(sh("Wang"));
//用等号把委托与一个方法关联
SayHello sh2 = c.SayHelloMethod;
Console.WriteLine(sh2("Liu"));
//委托与一个匿名方法关联
SayHello sh3 = delegate(string var)
{
Console.WriteLine("sh3!");
return var + ",how are you?";
};
Console.WriteLine(sh3("Jiang"));
//组合委托,此时委托就能够依次执行多个方法
NumberHandle nh = new NumberHandle(c.DoubleNumber);
NumberHandle nh2 = c.TrebleNumber;
NumberHandle nh3 = nh + nh2;
int num = 2;
nh3(ref num);
Console.WriteLine(""+num);
//组合委托,若委托的方法有返回值,则返回值为最后一个被执行方法的返回值
SayHello sh4 = sh + sh3;
Console.WriteLine(sh4("Zheng"));
//lambda表达式:另一种把委托与匿名方法关联起来的方法
SayHello sh5 = var => var + ",Hello lambda";
Console.WriteLine(sh5("Guo"));
Console.ReadLine();
}
}
delegate string SayHello(string val);
delegate void NumberHandle(ref int num);
class Class1
{
public string SayHelloMethod(string name)
{
Console.WriteLine("SayHello Method!");
return name + ",Hello!";
}
public void DoubleNumber(ref int num)
{
Console.WriteLine("Double it!");
num *= 2;
}
public void TrebleNumber(ref int num)
{
Console.WriteLine("Treble it!");
num *= 3;
}
}
}