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等访问权限。

Ctypedef不支持静态函数,Delegate支持静态函数

DDelegate是观察设计模式的产物。

EDelegate可委托其他对象的执行函数。

4 委托设计模式说明

Delegate的设计思想是观察模式,此模式模型如下:

 

A)  此处Delegate充当Obeserver观察者的角色。

B)   Delegate通过 +=或者-= 将需要观察的对象attach或Dettach 到列表中.

C)  当需要通知对象时,Delegate通过Notify群发消息通知Object采取措施。


欢迎关注微信公众号:




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值