c#Action和Func
Action
- 1.Action说明
- Action是.NET Framework内置的泛型委托,可以使用Action委托以参数形式传递方法,而不用显示声明自定义的委托。封装的方法必须与此委托定义的方法签名相对应。也就是说,封装的方法必须具有一个通过值传递给它的参数,并且不能有返回值。
- 2.Action 的特点
-
1.参数个0~16
-
2.没有返回值.
-
3例子
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ActionDemo : MonoBehaviour
{
Action action;//表示无参
Action<int> action1;//表示有传入参数int
void Start()
{
action = actionH1;//没有参数
action();
action1 = actionH2;//一个 int参数
action1(456);
actionH3(() => { Debug.Log("执行完actionH3了"); });//lambda 表达式 来执行委托
actionH3(actionH4);//执行完 actionH3后回调 actionH4方法
}
private void actionH1()//没有参数
{
Debug.Log(123);
}
private void actionH2(int index)//参数int
{
Debug.Log(index);
}
private void actionH3(Action act)//参数 Action
{
Debug.Log("在执行actionH3");
act();//回调 这个 委托方法
}
private void actionH4()//执行完 actionH3后的回调执行
{
Debug.Log("执行完actionH3了");
}
}
结果
delegate 和 Action 写法对比
delegate 写法
public delegate void CommonDelegate(string str);//定义委托
void Start()
{
CommonDelegate common = Init;//实例化委托
common("hello world");//执行
}
private void Init(string str)//放发
{
Debug.Log(str);//打印
}
修改为Action 写法
void Start()
{
Action<string> act = Init;
act("hello world");
}
private void Init(string str)//放发
{
Debug.Log(str);//打印
}
Action 代码更简洁点
Func
Func和Action相同点 :
1. 都是0~16个参数
不同点:
1.Func是有返回值的 而Action没有
Func的返回值
-
Func< T1 > (有返回值)------无参数类型,T1为返回值类型
-
Func<T1,T2>(有返回值)------T1为0-16个参数类型,T2为返回值类型
-
Func<T1,T2,T3>(有返回值)------T1和T2为0-16个参数类型,T3为返回值类型
-
也就是说 参数最后一位就是返回值类型(返回值的类型和Func输出参数类型相同)
Func<int【参数类型】,……,bool【最后一个是返回值类型】】> func
代码示例
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FuncDemo : MonoBehaviour
{
/*
Func<参数.....> //参数最后一位就是 委托的 返回类型
*/
void Start()
{
Func<string> MyFun1 = MyMethodA;//这样定义 就是 无参的Func 返回一个string
Debug.Log(MyFun1());//执行 这个委托
Func<string,string> MyFun2 = MyMethodB;//这样定义 就是参数为string的Func 返回一个string值
Debug.Log(MyFun2("一个参数"));//执行 这个委托
//一次类推
Func<string, string,bool> MyFun3 = MyMethodC;//这样定义 就是2个参数为string的Func 返回一个bool值
Debug.Log(MyFun3("一个参数","二个参数"));//执行 这个委托
}
//无参 返回string
private string MyMethodA()
{
return "MyMethodA--> hello world";
}
//一个string参数 +返回值string值
private string MyMethodB(string arg)
{
return "MyMethodB--> hello world " + arg;
}
//两个string参数 +返回bool值
private bool MyMethodC(string arg1, string arg2)
{
Debug.Log("MyMethodC--> hello world " + arg1 + " " + arg2);
return true;
}
}
运行结果
简单的来说
有返回值就用Func,无返回值就用Action