delegate
最基本的委托形式,必须要先定义委托
class DelegateDemo
{
//定义委托
public delegate void Run();
public Run r;
public DelegateDemo()
{
addDelegate(run1);
addDelegate(run2);
addDelegate(run3);
addDelegate(run4);
addDelegate(run4);
r();
}
void addDelegate(Run fun)
{
if (r == null)
{
r = fun;
}
else
{
r += fun;
}
}
public void run1()
{
Console.WriteLine("Delegate_1");
}
public void run2()
{
Console.WriteLine("Delegate_2");
}
public void run3()
{
Console.WriteLine("Delegate_3");
}
public void run4()
{
Console.WriteLine("Delegate_4");
}
}
action
委托的泛型,具有N个参数可以指定,不能指定返回值
class ActionDemo
{
public Action<string> act;
public ActionDemo()
{
addDelegate(run1);
addDelegate(run2);
addDelegate(run3);
addDelegate(run4);
addDelegate(run4);
act("a");
}
void addDelegate(Action<string> fun)
{
if (act == null)
{
act = fun;
}
else
{
act += fun;
}
}
public void run1(string key)
{
Console.WriteLine("Action_1");
}
public void run2(string key)
{
Console.WriteLine("Action_2");
}
public void run3(string key)
{
Console.WriteLine("Action_3");
}
public void run4(string key)
{
Console.WriteLine("Action_4");
}
}
Func
委托的泛型,具有N个参数并返回 TResult 参数指定的类型值的方法
class FuncDemo
{
public Func<string, int> act;
public FuncDemo()
{
addDelegate(run1);
addDelegate(run2);
addDelegate(run3);
addDelegate(run4);
addDelegate(run4);
act("a");
}
void addDelegate(Func<string, int> fun)
{
if (act == null)
{
act = fun;
}
else
{
act += fun;
}
}
public int run1(string key)
{
Console.WriteLine("Func_1");
return 0;
}
public int run2(string key)
{
Console.WriteLine("Func_2");
return 0;
}
public int run3(string key)
{
Console.WriteLine("Func_3");
return 0;
}
public int run4(string key)
{
Console.WriteLine("Func_4");
return 0;
}
}