// 1 泛型委托--Func Action
// 2 Func Action 异步多线程
class Program
{
static void Main(string[] args)
{
MyDelegate myDelegate = new MyDelegate();
myDelegate.Show();
Console.ReadKey();
}
}
class MyDelegate
{
public void Show()
{
{
//Action Func .NetFramework3.0出现的
//Action和Func 框架预定义的,新的API一律基于这些委托来封装
//Action 系统提供 0到16个泛型参数 不带返回值 委托
//Action action = new Action(DoNothing);
Action action = DoNothing; //是个语法糖,编译器帮我们添加上new Action
Action<int> action1 = ShowInt;
action1(1);
Action<int, string, Boolean, DateTime, long, int, string, Boolean, DateTime, long, int, string, Boolean, DateTime, long, string> action16 = null;
//Func 系统提供 0到16个泛型参数 带泛型返回值 委托
//Func 无参数有返回值
Func<int> func = Get;
int iResu = func.Invoke();
//Func 有参数有返回值
Func<int, string> func1 = ToString;
string sResu = func1.Invoke(1);
Func<int, string, Boolean, DateTime, long, int, string, Boolean, DateTime, long, int, string, Boolean, DateTime, long, string, string> func16 = null;
}
{
//多播委托有啥用呢?一个委托实例包含多个方法,可以通过+=/-=去增加/移除方法,Invoke时可以按顺序执行全部动作
//多播委托:任何一个委托都是多播委托类型的子类,可以通过+=去添加方法
//+= 给委托的实例添加方法,会形成方法链,Invoke时,会按顺序执行系列方法
Action method = this.DoNothing;
method += Study;
method += new MyDelegate().StudyAdvanced;
//method.BeginInvoke(null, null);//启动线程来完成计算 会报错,多播委托实例不能异步
foreach (Action item in method.GetInvocationList())
{
item.Invoke();
item.BeginInvoke(null, null); //异步执行委托
}
//method.Invoke();
Console.WriteLine("分割线----------------------------");
//-= 给委托的实例移除方法,从方法链的尾部开始匹配,遇到第一个完全吻合的,移除,且只移除一个,如果没有匹配,就什么也不发生
method -= this.DoNothing;
method -= Study;
method -= new MyDelegate().StudyAdvanced;//去不掉 原因是不同的实例的相同方法,并不吻合
method.Invoke();
//如果中间出现未捕获的异常,直接方法链结束了
Console.WriteLine("分割线----------------------------");
{
Func<int> func = this.Get;
func += this.Get2;
func += this.Get3;
int iResult = func.Invoke();
Console.WriteLine(iResult);
//结果是3 以最后一个为准,前面的丢失了。。所以一般多播委托用的是不带返回值的
}
}
}
public void ShowInt(int i)
{
Console.WriteLine(i);
}
public string ToString(int i)
{
return i.ToString();
}
public int Get()
{
return 1;
}
public int Get2()
{
return 2;
}
public int Get3()
{
return 3;
}
public void StudyAdvanced()
{
Console.WriteLine("StudyAdvanced");
}
public void Study()
{
Console.WriteLine("Study");
}
public void DoNothing()
{
Console.WriteLine("this is DoNothing");
}
}