Action、Func、Predicate都是对delegate的封装。
委托的特点:
委托类似于 C++ 函数指针,但它们是类型安全的。
委托允许将方法作为参数进行传递。
委托可用于定义回调方法。
委托可以链接在一起;例如,可以对一个事件调用多个方法。
方法不必与委托签名完全匹配。
1、delegate 抽象方法=》只写方法,不写实现部分。两种定义的方法:
① private delegate void MyDelegate(string n);
直接定义参数为string类型的委托
MyDelegate myDelegate;
实例化委托变量
② private delegate void MyDelegate<T>(T n);
定义参数为泛型的委托
MyDelegate <string> myDelegate;
绑定事件: 通过委托变量+=方法名
2、Action
Action <string> action; =》<参数>
①参数为泛型② 无返回值的系统定义的委托,不用自己再定义委托。
3、Func
Func<string,string> func; =》<参数,返回值>
①参数为泛型② 有返回值的系统定义的委托,不用自己再定义委托。
4、Predicate
Predicate<string> predicate;
①参数为泛型② 返回值为bool的系统定义的委托,不用自己再定义委托。
5、Lambda
委托绑定方法:
Action <string> action;
action += (a) => { Debug.Log(a + " 22222222222222"); };
① (形参)
② => 右结合运算符,和 = 优先级相同 。
③ {方法实现体;}
具体代码如下 :(Unity环境)
private delegate void MyDelegate(string n);
MyDelegate myDelegate;
Action <string> action;
Func<string,string> func;
Predicate<string> predicate;
void Start () {
myDelegate += delegateAction;
action += ActionAction;
func += funAction;
predicate += predicateAction;
myDelegate("1");
action("2");
Debug.Log( func("3 Func"));
Debug.Log(predicate("4 "));
}
void delegateAction(string a)
{
Debug.Log(a+ "delegate");
}
void ActionAction(string a)
{
Debug.Log(a+ "action");
}
string funAction(string a)
{
return a;
}
bool predicateAction(string a)
{
Debug.Log(a+ "predicate");
return true;
}
打印结果: