版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
Delegates(委托)delegatetype,definesaprotocol,specifyingalistofparametertypesandareturntype.delegateintTransformer(intx);//methoddeclaration???TransformeriscalledamethodcallerdelegateinstanceclassTest{
staticvoidMain()
{
Transformert=Square;//createdelegateinstance
intresult=t(3);//Invokedelegate
Console.WriteLine(result);//9
}
staticintSquare(intx){returnx*x;}//targetmethod}Transformert=Square;//createdelegateinstanceTransformert=newTransformer(Square);thestatementsaboveplaythesamerole.theformerisshorthandforthelatter.t.Invoke(3);
t(3)plug-inmethodwithdelegateswriteautilitymethodnamedTransformthatappliesatransformtoeachelementinanintegerarray.TheTransformmethodhasadelegateparameter,forspecifyingaplug-intransform.寫一個名為Transform的函數(shù),對整型數(shù)組中的每個元素加1,利用委托作為Transform的一個形參。publicdelegateintTransformer(intx);classUtil{publicstaticvoidTransform(int[]values,Transformert){for(inti=0;i<values.Length;i++)values[i]=t(values[i]);}}classTest{staticvoidMain(){int[]values={1,2,3};Util.Transform(values,Square);foreach(intiinvalues)Console.Write(i+"");//149}
staticintSquare(intx){returnx*x;}}MulticastDelegates
多播委托;組播委托;多路廣播委托Alldelegateinstanceshavemulticastcapability,meaningthatadelegateinstancecanreferencealistoftargetmethods,SomeDelegated=SomeMethod1;d+=SomeMethod2;Removeoneoftargetmethodsfromadelegateinstance:d-=SomeMethod1;Targetmethods:
InstancevsstaticmethodBothinstancemethodsandstaticmethodscanbethetargetmethodsofadelegateinstance.TheinstancetowhichtheinstancemethodbelongsisreferencedbySystem.Delegateclass’sTargetproperty.classMyClass
{publicvoidfun(intx)
{Console.WriteLine(x);
}publicoverridestringToString()
{return"MyClass";
}
}classProgram
{delegatevoidmyDelegate(intx);staticvoidMain(string[]args)
{MyClassmc=newMyClass();myDelegatedel=newmyDelegate(mc.fun);//實例函數(shù)del.Invoke(20);//20Console.WriteLine(del.Target.GetType());//example.MyClassConsole.WriteLine(del.Target.ToString());//"MyClass"
}
}GenericdelegateTypespublicdelegateTTransformer<T>(Targ);staticdoublesqr(doublex){returnx*x;}staticvoidMain(){Transformer<double>s=Square;Console.WriteLine(s(3.3));//10.89}Func&ActionDelegatesFuncandActionarebothgenericdelegates,definedintheSystemnamespace.delegateTResultFunc<outTResult>();delegateTResultFunc<inT,outTResult>(Targ);delegateTResultFunc<inT1,inT2,outTResult>(T1arg1,T2arg2);...andsoon,uptoT16delegatevoidAction();delegatevoidAction<inT>(Targ);delegatevoidAction<inT1,inT2>(T1arg1,T2arg2);...andsoon,uptoT16publicstaticvoidfun<T>(T[]values,Func<T,T>transformer)
{for(inti=0;i<values.Length;i++)
{values[i]=transformer(values[i]);Console.WriteLine(values[i]);
}
}publicstaticdoubleadd(doublex){returnx+20;}staticvoidMain(string[]args)
{double[]arr=newdouble[]{1,2,3,4,5};fun<double>(arr,add);
}publicstaticvoidfun<T>(T[]values,Action<T>transformer)
{for(inti=0;i<values.Length;i++)
{transformer(values[i]);
}
}publicstaticvoidprint(doublex){Console.WriteLine(x);}staticvoidMain(string[]args)
{double[]arr=newdouble[]{1,2,3,4,5};fun<double>(arr,print);
}DelegateCompatibilitydelegatetypesareallincompatiblewitheachother,eveniftheirsignaturesarethesame.delegatevoidD1();delegatevoidD2();D1d1=Method1;D2d2=d1;//compile-timeerrorD2d2=newD2(d1);//permitted!!covariancefordelegatereturntypesdelegateobjectObjectRetriever();
staticvoidMain(){ObjectRetrievero=newObjectRetriever(GetString);objectresult=o();Console.WriteLine(result);//hello}staticstringGetString(){return"hello";}contravarianceforparametertypesadelegatetargetmethodmayhavelessspecificparametertypesthandescribedbythedelegate,calledcontravariance.delegatevoidStringAction(strings);...staticvoidMain(){StringActionsa=newStringAction(ActOnObject);sa("hello");}staticvoidActOnObject(objecto)//objectissmallerthanstring{Console.WriteLine(o);//hello}Event—在類里面用Eventsusethepublisher-subscriber
model.Apublisher
isanobjectthatcontainsthedefinitionoftheeventandthedelegate.Apublisherclassobjectinvokestheeventanditisnotifiedtootherobjects.Asubscriber
isanobjectthatacceptstheeventandprovidesaneventhandler.Thedelegateinthepublisherclassinvokesthemethod(eventhandler)ofthesubscriberclass.publicdelegatevoidPriceChangedHandler(decimaloldPrice,decimalnewPrice);(1)publicclassStock
{//publisher事件發(fā)布者stringsymbol;decimalprice;publicStock(stringsymbol){this.symbol=symbol;}publiceventPriceChangedHandlerPriceChanged;//一種特殊的委托,事件(2)publicdecimalPrice
{get{returnprice;}set{if(price==value)return;//fireeventifinvocationlistisnotemptyif(PriceChanged!=null)
PriceChanged(price,value);//在publisher---Stock中調(diào)用(3)price=value;
}
}
}publicstaticvoidchange(decimalx,decimaly)
{Console.WriteLine(y);
}publicstaticvoidup(decimalx,decimaly)
{Console.WriteLine("up");Console.WriteLine(y);
}staticvoidMain(string[]args)
{Stockst=newStock("LIU");st.PriceChanged+=change;//訂閱事件st.PriceChanged+=up;//在此處訂閱事件st.Price=20;
}StandardEventPatternTheNetFrameworkdefinesastandardpatternforwritingevents.eventsarebasedontheEventHandlerdelegateandtheEventArgsbaseclass.publicdelegatevoidEventHandler<TEventArgs>(objectsource,TEventArgse)whereTEventArgs:EventArgs;derivefromEventArgspublicclassPriceChangedEventArgs:EventArgs
{publicreadonlydecimalLastPrice,NewPrice;publicPriceChangedEventArgs(decimallastPrice,decimalnewPrice){LastPrice=lastPrice;NewPrice=newPrice;}
}definepublisherclasspublicclassStock
{stringsymbol;decimalprice;publicStock(stringsymbol){this.symbol=symbol;}publiceventEventHandler<PriceChangedEventArgs>PriceChanged;//EventHandlerisadelegateprotectedvirtualvoidOnPriceChanged(PriceChangedEventArgse)//here,fireanevent
{if(PriceChanged!=null)PriceChanged(this,e);
}publicdecimalPrice
{get{returnprice;}set
{if(price==value)return;OnPriceChanged(newPriceChangedEventArgs(price,value));price=value;
}
}
}definesubscribersstaticvoidstock_price_changed(objectsender,PriceChangedEventArgse)
{if((e.NewPrice-e.LastPrice)/e.LastPrice>0.1M)Console.WriteLine("Alert,10%priceincrease!");
}staticvoidMain(string[]args)
{Stockst=newStock("LIU");st.Price=27.10M;Console.WriteLine("OK");st.PriceChanged+=stock_price_changed;st.Price=31.59M;
}nongenericEventHandlerdelegateThismeansthatnoadditionalinformationneedbetransmittedwithevent.publiceventEventHandlerPriceChanged;EventAccessorsAnevent’saccessors
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 蒸發(fā)濃縮結(jié)晶工誠信模擬考核試卷含答案
- 機電設(shè)備維修工崗前安全規(guī)程考核試卷含答案
- 掘進及鑿巖機械裝配調(diào)試工10S執(zhí)行考核試卷含答案
- 漆器鑲嵌裝飾工班組建設(shè)強化考核試卷含答案
- 殘疾人就業(yè)輔導(dǎo)員安全防護測試考核試卷含答案
- 鉑金期貨合同范本
- 承包門診合同協(xié)議
- 駕校保潔合同范本
- 采購合同保密協(xié)議
- 馬匹轉(zhuǎn)讓合同范本
- 期末綜合測評卷一(試卷)2025-2026學(xué)年三年級語文上冊(統(tǒng)編版)
- 數(shù)據(jù)資產(chǎn)管理實踐指南8.0
- 2025年非遺文化(文化傳承)項目可行性研究報告
- 糖尿病患者的精細化護理與血糖管理
- 宇宙星空教學(xué)課件
- 未來醫(yī)學(xué)行業(yè)發(fā)展趨勢分析報告
- 中國企業(yè)科創(chuàng)力研究報告2025
- 低空經(jīng)濟產(chǎn)業(yè)綜合示范區(qū)建設(shè)項目投資計劃書
- 校長職級制筆試題目及答案
- 2026福建泉州市選優(yōu)生選拔引進筆試考試備考試題及答案解析
- 湖南中考生物真題三年(2023-2025)分類匯編:專題10 生物的遺傳和變異(原卷版)
評論
0/150
提交評論