C#之委托delegate
1 委托实现
委托,顾名思义。通过授权方式将事务处理功能交由受托方。通过受托方触发响应机制。
定义格式如下:
public delegate void MyDelegate();
工程实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KnowDelegate
{
class Program
{
publicdelegatevoid MyDelegate();
privatevoid Show()
{
Console.WriteLine("This is functionshow");
}
privatestaticvoid StaticShow()
{
Console.WriteLine("This is fuction staticshow");
}
staticvoid Main(string[] args)
{
var p =new Program();
MyDelegate del =new MyDelegate(p.Show);
del +=Program.StaticShow;
del.Invoke();
}
}
}
2 C++中typedef的定义及实现
#include"stdafx.h"
#include<iostream>
using namespace std;
typedef void(*fun)();
void Show()
{
cout<<"This is the real running function."<<endl;
}
int main()
{
funf = Show;
f();
return 0;
}
3 委托与typedef的区别
A)typedef 是函数指定的引用,只能一对一的赋值调用。Delegate支持一对多可用通过 +=增加委托函数,也可以通过-=减少委托函数
B)typedef 不支持private等访问权限修饰。Delegate支持private等访问权限。
C)typedef不支持静态函数,Delegate支持静态函数
D)Delegate是观察设计模式的产物。
E)Delegate可委托其他对象的执行函数。
4 委托设计模式说明
Delegate的设计思想是观察模式,此模式模型如下:
A) 此处Delegate充当Obeserver观察者的角色。
B) Delegate通过 +=或者-= 将需要观察的对象attach或Dettach 到列表中.
C) 当需要通知对象时,Delegate通过Notify群发消息通知Object采取措施。
欢迎关注微信公众号: