蓝鸥Unity开发基础二——课时26 委托
一、委托
委托是一种特殊的类型,用于引用方法
定义委托需要用delegate关键词
委托可以把方法当做参数来传递
委托可以使用+-运算符合并,解绑委托
推荐视频讲师博客:http://11165165.blog.51cto.com/
using System;
namespace Lesson_26
{
//定义委托——访问修饰符delegate,返回值类型 委托名(参数列表);
public delegate void Something (string name);
public class Student{
//可以像普通类型一样当做方法参数传递
public void Do(Something something){
//真正调用了方法A——方法回调
something (name);
}
//可以
public Student(string name){
//可以像普通方法一样调用
this.name=name;
}
private string name;
}
public class Teacher{
public void Hungry(){
Student s = new Student ("老王");
//创建委托变量
Something a = new Something (A);
Something b = new Something (B);
Something c = b+a ;
c = c - a;
s.Do (c);
}
public void A(string name){
Console.WriteLine ("Hello,"+name);
}
public void B(string name){
Console.WriteLine (name+"跑十圈");
}
}
class MainClass
{
public static void Main (string[] args)
{
Teacher t = new Teacher ();
t.Hungry ();
}
}
}
原文地址:http://11131960.blog.51cto.com/11121960/1850594