作用:
如果要把方法作为参数进行传递,就要用委托. 委托是一个类型,可以赋值一个方法的引用.通过delegate
来声明.
创建委托:
方式1: delegate void MyDelegate1( int x )
方式1: delegate void MyDelegate2( T x )
使用委托:
方式1: MyDelegate1 mydelegate = new MyDelegate1 (func)
方式1: MyDelegate1 mydelegate = func
委托无参数:
public delegate void ShowDelegate();//创建了一个委托
public void Show1()
{
//这是一个方法
}
// Use this for initialization
void Start () {
ShowDelegate show = Show1; //这时候show = Show1的方法
if(show != null){
show(); //执行委托(执行Show1的方法)
show.Invoke(); //执行委托(执行Show1的方法)
}
show?.Invoke(); //不等于空调用简写
}
委托带参数的
public delegate void ShowDelegate(int a,int b);//创建了一个委托
public void Show1(int a, int b)
{
//这是一个方法
}
// Use this for initialization
void Start () {
ShowDelegate show = Show1; //这时候show = Show1的方法
show(1,2); //执行委托(执行Show1的方法)
show.Invoke(1,2); //执行委托(执行Show1的方法)
show?.Invoke(1,2); //不等于空调用简写
}
委托有返回值
public delegate int ShowDelegate(int a);//创建了一个委托
public int Show1(int a)
{
//这是一个方法
return a;
}
// Use this for initialization
void Start () {
ShowDelegate show = Show1; //这时候show = Show1的方法
int a = show(1); //执行委托(执行Show1的方法)
int b = show.Invoke(1); //执行委托(执行Show1的方法)
int c = show?.Invoke(1); //不等于空调用简写
}
委托泛型
public delegate void ShowDelegate<T>(T a);//创建了一个委托
public void Show1(string a)
{
//这是一个方法
Debug.Log("委托泛型 a-> :"+ a);
}
// Use this for initialization
void Start () {
ShowDelegate<string> show = Show1; //这时候show = Show1的方法
show("hello"); //执行委托(执行Show1的方法)
show.Invoke("hello"); //执行委托(执行Show1的方法)
}