委托(delegate)
C#中委托与c++中的函数指针类似,是存有对某个方法引用的引用类型
用法:权限修饰符 delegate 函数返回值类型 委托名(函数形参)
public delegate void TestDelegate();//声明委托
class Cat
{
public void CatCall()
{
Console.WriteLine("CatCall");
}
}
static void Main(string[] args)
{
Cat ct = new Cat();
TestDelegate t1 = new TestDelegate(ct.CatCall);//将CatCall绑定到委托上
t1(); //执行委托 输出CatCall
}
系统自带的委托
Func<函数参数类型,.....,返回值类型> 有返回值
Action<函数参数类型...> 无返回值
Predicate :返回值为bool(很少用,其功能可以被Func代替)
static void Main(string[] args)
{
//返回值为int 形参为一个int的匿名方法的委托
Func<int,int, int> f1 = new Func<int, int,int>(delegate(int a,int b) { return a*b; });
//无返回值 形参为一个int的匿名方法的委托
Action<int> action = new Action<int>((int a) => { Console.WriteLine("{0}", a); });
//返回值默认且必须为bool 形参可以自定义类型
Predicate<int> p1=new Predicate<int>(delegate(int a){return a==1;});
Console.WriteLine( p1(1));// true
Console.WriteLine(f1(2,4)); //8
action(5); //5
匿名方法
匿名方法是没有名称只有主体的方法,同时匿名方法不需要返回值类型,匿名方法的返回值类型是根据主体中return语句来推断的
匿名方法是通过delegate关键字来实现的
匿名函数只能将方法赋值给委托,通过委托调用该方法
public delegate void TestDelegate();
static void Main(string[] args)
{
//匿名方法实现 作为参数传递给委托
TestDelegate t2 = new TestDelegate(delegate(){ Console.WriteLine("匿名方法测试"); });
t2();//执行委托 输出:匿名方法测试
lambda表达式
lambda也是匿名方法的一种,在Lambda表达式中可以包含语句以及运算等操作。并且可用于创建委托
public delegate void TestDelegate();
static void Main(string[] args)
{
//C#中的lambda表达式
TestDelegate t3 = new TestDelegate(() => { Console.WriteLine("lambda表达式测试"); });
t3(); //输出 lambda表达式测试
多播委托
1.将许多相同类型的委托合并在一起,通过+=合并一个委托,-=撤销一个委托
2.多播委托是有执行顺序的,大体上表现为先+=的委托先执行,后加减的委托后执行。
public delegate void TestDelegate();
static void Main(string[] args)
{
TestDelegate t2 = new TestDelegate(delegate() { Console.WriteLine("匿名函数测试"); });
TestDelegate t3 = new TestDelegate(() => { Console.WriteLine("lambda表达式测试"); });
t2 += t3; //将t3合并到t2上
t2(); //先执行t2 再执行t3
t2-=t3;//将t3从t2上注销 输出:匿名函数测试 lambda表达式测试
t2();// 输出:匿名函数测试
事件(event)
事件指的是用户的一个操作,例如按键,鼠标点击,鼠标移动,或者是一些提示信息,如系统生成的通知。应用程序需要在事件发生时响应事件
事件是基于委托的,是委托的一种签名
使用:
权限修饰符 event 一种委托类型 事件名
//该例子类似观察者模式
public delegate void TestDelegate(); //委托声明
class Cat
{
public event TestDelegate CatCallEvent; //事件声明基于TestDelegate 委托
public void CatCall()
{
Console.WriteLine("CatCall");
if(CatCallEvent!=null) //判断事件是否为空
{
CatCallEvent(); //响应事件
}
}
}
class Mouse
{
public void run()
{
Console.WriteLine("Mouse run");
}
}
class Person
{
public void WakeUp()
{
Console.WriteLine("Person WakeUp");
}
}
static void Main(string[] args)
{
Person p = new Person();
Mouse m1 = new Mouse();
Cat ct = new Cat();
ct.CatCallEvent += new TestDelegate(m1.run); //将委托合并如事件中
ct.CatCallEvent += new TestDelegate(p.WakeUp);
ct.CatCall(); //执行方法 连带委托一起执行 输出 CatCall Mouse run Person WakeUp
}