« | July 2025 | » | 日 | 一 | 二 | 三 | 四 | 五 | 六 | | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | | | |
| 公告 |
谦卑,荣誉,牺牲,英勇,怜悯,诚实,精神,公正。 |
Blog信息 |
blog名称: 日志总数:183 评论数量:698 留言数量:7 访问次数:3016625 建立时间:2005年12月29日 |

| |
[我的笔记]笔记3.14 读书笔记
newqiang 发表于 2006/3/15 8:38:35 |
1. 委托是类型安全的,面向对象的回调函数。委托也是更详尽的回调协议——事件的基础。 毁掉函数是这样的一个函数:程序首先用某种方式描述和登记某个函数,然后由另外一个程序调用它。在c和 c++中,用函数的指针来实现回调功能。 声明一个委托:__delegate void NotifyCallback(Decimal balance); 定义一个委托:创建一个委托时,需要指定一个回调方法,该方法必须与委托声明中的签名匹配,可以是静态方法,也可以使实例方法。如下: static void NotifyCustomer(Decimal balance) { Console::WriteLine("Dear customer"); } void NotifyInstance(Decimal balance) { Console::WriteLine("Dear customer"); }
创建一个委托对象:可以像创建任何其他类的实例一样,用new操作符创建一个委托对象。 //Create delegate for static method NotifyCustomer NotifyCallback *pCustDlg = new NotifyCallback(0,NotifyCustomer); //Create delegate for instance method NotifyInstance NotifyCallback *pInstDlg = new NotifyCallback(pda,NotifyInstance);
调用一个委托:可以像调用方法那样调用委托。委托对象不是一个方法,但是他又一个封装的方法,委托对象将对他的调用委托到期封装的方法,故而叫做“委托”。下面代码中:委托对象notifyDlg在SetDelegate方法中初始化,在Withdraw中调用。 __gc class Account { private: Decimal balance; NotifyCallback *pNotifyDlg; ... } void SetDelegate(NotifyCallback *pDlg) { pNotifyDlg = pDlg; ... } void Withdraw(Decimal amount) { balance = balance - amount; if (balance <0) //overdraft situation pNotifyDlg(balance);//callback }
合并委托对象: pCurrDlg = static_cast<NotifyCallback *>(Delegate::Combine(pCustDlg,pBankDlg)); pCurrDlg = static_cast<NotifyCallback *>(Delegate::Remove(pCustDlg,pBankDlg)); |
|
|