委托系列05-Action/Func
一、为什么会有Action和Func
二、Action和Func的声明及区别
1、Action
1、普通委托的声明和调用
委托:
///
/// 无参数无返回值委托
///
public delegate void NoParamNoReturnDelegate();
///
/// 有参数无返回值委托
///
///
public delegate void WithParamNoReturnDelegate(int i);
方法:
///
/// 无参数无返回值方法
///
private void NoParamNoReturnFun()
{
}
///
/// 有参数无返回值方法
///
///
private void WithParamNoReturnFun(int i)
{
Console.WriteLine("This is DoNothing");
}
调用:
NoParamNoReturnDelegate NoParamNoReturnDelegate = new NoParamNoReturnDelegate(NoParamNoReturnFun);
NoParamNoReturnDelegate.Invoke();
WithParamNoReturnDelegate WithParamNoReturnDelegate = new WithParamNoReturnDelegate(WithParamNoReturnFun);
WithParamNoReturnDelegate.Invoke(10);
2、Actio委托声明和调用
Action action = new Action(NoParamNoReturnFun);
action.Invoke();
Action action1 = new Action(WithParamNoReturnFun);
action1.Invoke(10);
3、总结
??从上图可以看得出来,下面两种方式都可以调用NoreturnNopara方法,效果是一样的。
ShowDelegate showDelegate = new ShowDelegate(NoreturnNopara);
showDelegate.Invoke();
Action action = new Action(NoreturnNopara);
action.Invoke();
2、Func
1、普通委托的声明和调用
委托:
///
/// 无参数有返回值委托
///
///
public delegate int NoParamWithReturnDelegate();
///
/// 有参数有返回值委托
///
///
///
public delegate int WithParamWithReturnDelegate(int i);
方法:
///
/// 无参数有返回值方法
///
///
private int NoParamWithReturnFun()
{
return 0;
}
///
/// 有参数无返回值方法
///
///
///
private int WithParamWithReturnFun(int i)
{
return 0;
}
调用:
//无参数有返回值
NoParamWithReturnDelegate NoParamReturnDelegate = new NoParamWithReturnDelegate(NoParamWithReturnFun);
NoParamReturnDelegate.Invoke();
//有参数有返回值
WithParamWithReturnDelegate WithParamWithReturnDelegate = new WithParamWithReturnDelegate(WithParamWithReturnFun);
WithParamWithReturnDelegate.Invoke(10);
1、Func委托的声明和调用
//无参数有返回值Func
Func func1 = new Func(NoParamWithReturnFun);
func1.Invoke();
//无参数有返回值Func
Func func2 = new Func(WithParamWithReturnFun);
func2.Invoke(10);
//多个参数的Func委托
Func func3 = new Func(DoNothingIntAndStringWithReturn);
func3.Invoke(10,"test");
Func, DateTime, object, int, string, DateTime, object, int, string, DateTime, object, int, string, DateTime, object, int> func4 = null;
2、总结
??从上图可以看得出来,下面两种方式都可以调用NoreturnNopara方法,效果是一样的。
//无参数有返回值
NoParamWithReturnDelegate NoParamReturnDelegate = new NoParamWithReturnDelegate(NoParamWithReturnFun);
NoParamReturnDelegate.Invoke();
//有参数有返回值
WithParamWithReturnDelegate WithParamWithReturnDelegate = new WithParamWithReturnDelegate(WithParamWithReturnFun);
WithParamWithReturnDelegate.Invoke(10);
//无参数有返回值Func
Func func1 = new Func(NoParamWithReturnFun);
func1.Invoke();
//无参数有返回值Func
Func func2 = new Func(WithParamWithReturnFun);
func2.Invoke(10);
3、区别
Action:
- 1.Action是来自于System.RunTime的一个声明好的可以带有一个或者多个参数的委托delegate
- 2.Action是没有返回值的委托
- 3.最多支持16个入参
- 4.想要支持更多的参数呢、---就可以自己些--也只是定义一个委托而已,只是多了一个参数
Func:
- 1.Func是来自于System.RunTime的一个声明好的可以有返回值的委托delegate,也可以有参数
- 2.Action是没有返回值的委托
- 3.尖括号中的第一个是输入参数,第二个是返回值
- 4.如果尖括号中只有一个参数,那就是返回值类型,没有输入参数
- 5.最多支持16个入参
- 6.想要支持更多的参数呢、---就可以自己些--也只是定义一个委托而已,只是多了一个参数