v 版5章節(jié)教材課件_第1頁
v 版5章節(jié)教材課件_第2頁
v 版5章節(jié)教材課件_第3頁
v 版5章節(jié)教材課件_第4頁
v 版5章節(jié)教材課件_第5頁
已閱讀5頁,還剩177頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

主講教師:本課學(xué)時:聯(lián)系方式:C#程序設(shè)計教程第五章深入了解C#面向?qū)ο缶幊?/p>

CONTENT本章主要內(nèi)容介紹5.1C#繼承機(jī)制

5.2C#多態(tài)

機(jī)制5.3操作符重載

5.4結(jié)構(gòu)5.5枚舉5.6接口5.7委托5.8事件

5.9索引器

5.10異常處理

5.11組件與程序集

5.12小結(jié)本章學(xué)習(xí)目標(biāo):理解C#的繼承性和多態(tài)性掌握操作符重載的方法熟練掌握用接口的定義與使用熟練掌握委托的使用初步掌握事件的機(jī)制熟練掌握索引器的定義與使用理解異常處理和組件5.1C#繼承機(jī)制

在這個世界上,人可以分多種,但是卻有很多共同點(diǎn)。例如人一般都有名字,身份證,父母。但是,一個成功的人除了有名字,身份證,父母外,還有輝煌的事業(yè)。也就是他是普通人,也是成功的人。這類似與繼承的原理。生活例子:5.1C#繼承機(jī)制

繼承是面向?qū)ο蠹夹g(shù)最有特色、最重要、也是與傳統(tǒng)編程方法最不相同的。繼承表示了實(shí)體間的一種層次關(guān)系?;?父類,派生類/子類派生類可以繼承基類的特征和能力,如屬性和方法。派生類還可以添加新的特性或者是修改已有的特性以滿足特定的要求,但不能刪除基類的成員。一個父類可以有多個子類。父類是所有子類公共特征的集合,子類則是父類的特殊化。C#中每個子類只能有一個基類,即不允許多重繼承繼承的好處:實(shí)現(xiàn)了代碼重用派生類可以繼承基類中除構(gòu)造函數(shù)和析構(gòu)函數(shù)外的所有可訪問的成員訪問修飾符protected的作用子類可以訪問,其他的類都不可以訪問繼承是可傳遞的P108基類與派生類之間的轉(zhuǎn)換基類與派生類間的轉(zhuǎn)換隱式轉(zhuǎn)換派生類基類顯式轉(zhuǎn)換基類派生類(有條件)Parentp=newChild();Childc=(Child)p;Parentp=newParent();Childc=(Child)p;X拋出異常:InvalidCastException繼承

ClassBase{//成員變量intbasevar;//成員函數(shù)Base_fun1(){//定義}

…….

…….ClassDerived:Base{//成員變量intderivedvars;//成員函數(shù)Derived_fun1(){//定義}

…….

…….基類voidmain(){Deriveddr_obj=newDerived();dr_obj.Base_fun1();}無需重新編寫代碼派生類狗馬繼承動物基類派生類繼承的層次結(jié)構(gòu)示例ClassAnimal{ //成員變量 inteyes,nose; Animal() { eyes=2; nose=1; } Pet_Animal() { //定義 }}基類ClassDog:Animal{//成員變量

//成員函數(shù)

privateBarking(){ //定義}

privateWagging_Tail(){}}派生類繼承C#中的類

publicclass

Graduate:Student,Employee{

//成員變量

//成員函數(shù)}

多重繼承允許多重接口實(shí)現(xiàn)X演示publicclassStudent:Person{privatestring_school;privateuint_eng;privateuint_math;privateuint_sci;

publicvoidGetMarks(){ Console.WriteLine(“請輸入學(xué)校名稱");

_school=Console.ReadLine();

Console.WriteLine("請分別輸入英語、數(shù)學(xué)和自然科學(xué)的分?jǐn)?shù)。");

_eng=uint.Parse(Console.ReadLine());

_math=uint.Parse(Console.ReadLine());

_sci=uint.Parse(Console.ReadLine());

Console.WriteLine(“所得總分為:{0}",_eng+_math+_sci);

}}派生類publicclassPerson{privatestring_name;privateuint_age;publicvoidGetInfo(){Console.WriteLine("請輸入您的姓名和年齡");

_name=Console.ReadLine();

_age=uint.Parse(Console.ReadLine());

}

publicvoidDispInfo()

{

Console.WriteLine("尊敬的{0},您的年齡為{1}",_name,_age);}}基類staticvoidMain(string[]args){StudentobjStudent=newStudent();objStudent.GetInfo(); objStudent.DispInfo(); objStudent.GetMarks();}調(diào)用的基類成員無法實(shí)現(xiàn)

GetInfo()和DispInfo()方法輸出結(jié)果:演示publicclassPerson{ privatestring_name; privateuint_age; publicvoidGetInfo() { Console.WriteLine("請輸入您的姓名和年齡");

_name=Console.ReadLine();

_age=uint.Parse(Console.ReadLine());

}

publicvoidDispInfo()

{

Console.WriteLine("尊敬的{0},您的年齡為{1}", _name,_age); }}publicclassStudent:Person{privatestring_school;privateuint_eng;privateuint_math;privateuint_sci;privateuint_tot;publicuintGetMarks(){ Console.WriteLine(“請輸入學(xué)校名稱");

_school=Console.ReadLine();

Console.WriteLine("請分別輸入英語、數(shù)學(xué)和自然科學(xué)的分?jǐn)?shù)。");

_eng=uint.Parse(Console.ReadLine());

_math=uint.Parse(Console.ReadLine());

_sci=uint.Parse(Console.ReadLine());

_tot=_eng+_math+_sci;

Console.WriteLine("所得總分為:{0}",_tot); return_tot;}}基類派生類publicclassUnderGraduate:Student{publicvoidChkEgbl(){ Console.WriteLine("要上升一級,要求總分不低于150"); if(this.GetMarks()>149) Console.WriteLine("合格");

else

Console.WriteLine(“不合格");

}}派生類publicstaticvoidMain(string[]args){ UnderGraduateobjUnderGraduate=newUnderGraduate(); objUnderGraduate.GetInfo(); objUnderGraduate.DispInfo(); objUnderGraduate.ChkEgbl();}輸出結(jié)果:用于從派生類中訪問基類成員可以使用base關(guān)鍵字調(diào)用基類的構(gòu)造函數(shù)關(guān)鍵字base調(diào)用

base構(gòu)造函數(shù)

publicclass

Student:Person{privateuintid;//調(diào)用Person構(gòu)造函數(shù)public

Student(string

name,uint

age,uint

id):base(name,age)

{

this.id=id; Console.WriteLine(id);}}

:base

關(guān)鍵字將調(diào)用

Person類構(gòu)造函數(shù)演示publicclassPerson{ publicstring_name; publicuint_age; publicPerson(stringname,uintage) { this._name=name; this._age=age; Console.WriteLine(_name); Console.WriteLine(_age); }}publicclassStudent:Person{ privateuint_id; publicStudent(stringname,uintage,uintid):base(name,age) { this._id=id; Console.WriteLine(_id); }}還將調(diào)用Base構(gòu)造函數(shù)staticvoidMain(string[]args){ //構(gòu)造Student StudentobjStudent=newStudent("XYZ",45,001);}輸出結(jié)果:輸出結(jié)果:5.2C#多態(tài)機(jī)制課堂上,老師給出很多個函數(shù),他們的作用都是比較大小。這些函數(shù)的名稱都相同,不同的的是參數(shù)的類型,個數(shù)和函數(shù)的返回值。過后,老師有些出一大堆數(shù)據(jù),它們有整形,單精度,雙精度等。而同學(xué)們要根據(jù)這些數(shù)據(jù)找出相應(yīng)的函數(shù),最終根據(jù)那個函數(shù)判斷大小。這等同于多態(tài)的原理。生活例子:5.2C#多態(tài)機(jī)制多態(tài)(Polymorphism):多態(tài)的意思是事物具有不同形式的能力。例如,對不同的實(shí)例,某個操作可能會有不同的行為。這個行為依賴于所要操作數(shù)據(jù)的類型。多態(tài)機(jī)制使具有不同內(nèi)部結(jié)構(gòu)的對象可以共享相同的外部接口。如何實(shí)現(xiàn)多態(tài)C#中有兩種實(shí)現(xiàn)多態(tài)的方法通過繼承實(shí)現(xiàn)多態(tài)通過重載實(shí)現(xiàn)多態(tài)通過繼承,可以用兩類方法來實(shí)現(xiàn)多態(tài)重寫基類的虛方法(虛方法重寫)重寫基類的抽象方法對基類虛方法的重寫基類和派生類中定義完全相同的兩個方法方法名相同對應(yīng)的參數(shù)相同返回值相同語法規(guī)定基類的方法必須用virtual修飾符定義為虛方法派生類必須用override修飾符重新定義該方法與非虛方法的比較usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceSamsung{classprogram{publicstaticvoidMain(string[]args){circlepan=newcircle();//實(shí)例化一個circle類的蘇對象pan

pan.L();

Console.WriteLine("pan的面積為{0}",pan.S());

wheelcarWheel=newwheel();//實(shí)例化一個wheel類的對象carWheel

carWheel.L();

Console.ReadKey();

}

}

publicclasscircle//定義一個circle(圓)的類{doublepi=3.14;//定義pi為double型,值為3.14doubler=0.0;//初始化半徑r

virtualpublicvoidL()

{

Console.Write("請輸入半徑r=");//在屏幕上輸出括號內(nèi)的字符串r=double.Parse(Console.ReadLine());Console.WriteLine("周長為{0}",2*pi*r);//計算周長并輸出}

對基類虛方法的重寫publicdoubleS(){Console.Write("請輸入半徑r=");//在屏幕上輸出括號內(nèi)的字符串r=double.Parse(Console.ReadLine());returnpi*r*r;}}publicclasswheel:circle{stringbrand;//派生類中新增加的屬性publicoverridevoidL(){Console.Write("輪子的品牌是:");brand=Console.ReadLine();base.L();//base關(guān)鍵字是用來調(diào)用基類的方法Console.WriteLine("{0}牌輪子還不錯",brand);

}

}}輸出的結(jié)果是usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceSamsung{classprogram{publicstaticvoidMain(string[]args){Parentp=newParent();Childc=newChild();Parentpc=c;p.HideFun();c.HideFun();pc.HideFun();Console.ReadKey();}}方法的隱藏classParent{publicvoidHideFun(){Console.WriteLine("父類Parent的HideFun方法");}}classChild:Parent{publicvoidHideFun(){Console.WriteLine("子類Chile的HideFun方法");}}}方法的隱藏輸出結(jié)果是:方法的隱藏派生類可以定義與基類具有相同簽名的方法new關(guān)鍵字派生類定義與基類具有相同簽名的方法時,需要使用new關(guān)鍵字,否則編譯器將給出警告方法的隱藏當(dāng)用派生類的對象訪問同名的方法時執(zhí)行派生類的方法?執(zhí)行基類的方法?對象變量.HideFun()由對象變量的類型決定調(diào)用方法說明p.HideFun()p是Parent,執(zhí)行Parent的HideFunc.HideFun()c是Child,執(zhí)行Child的HideFunpc.HideFun()pc是Parent,執(zhí)行Parent的HideFun實(shí)際上pc引用的是Child,因此本質(zhì)是Child。能否執(zhí)行Child的HideFun?基類與派生類的方法基類與派生類方法之間的關(guān)系類型說明擴(kuò)充是派生類新增的,基類沒有。重載派生類中有與基類同名的方法,但參數(shù)類型或個數(shù)不同完全相同派生類中定義了一個與基類相同的方法,即方法的原型完全相同隱藏可以聲明與繼承而來的同名的成員重寫基類的方法,屬性,索引器重新定義,而成員名和相應(yīng)的參數(shù)都不變用base調(diào)用的基類方法classVehicle{publicvirtualstringStart(){return"交通工具啟動";}}classCar:Vehicle{publicoverridestringStart(){return"汽車起步";}}classPlane:Vehicle{publicoverridestringStart(){return"飛機(jī)起飛";}}方法的重寫classProgram{staticvoidMain(string[]args){Vehicle[]v=newVehicle[3];v[0]=newVehicle();v[1]=newCar();v[2]=newPlane();foreach(Vehicleveinv){Console.WriteLine(ve.Start());}Console.ReadKey();}}輸出結(jié)果是:方法的重寫方法重寫對基類同名方法,用關(guān)鍵字virtual修飾,即虛方法對派生類同名方法,用關(guān)鍵字override修飾虛方法調(diào)用的特點(diǎn)由對象變量所引用的對象來決定執(zhí)行哪一個方法,而與對象變量本身的類型無關(guān)方法重寫是實(shí)現(xiàn)多態(tài)的一種方法多態(tài):用同樣的一個語句,執(zhí)行不同的操作。抽象類和抽象方法abstractclassClassOne{

//類實(shí)現(xiàn)}訪問修飾符派生類的基類不能實(shí)例化abstractclassBase{//成員變量intbasevar;//成員函數(shù)abstractvoidbase_fun1(parameters);

//無法實(shí)現(xiàn)

…….}抽象方法classDerived:Base{

//成員變量intderivedvars;

//成員函數(shù)override

voidBase_fun1(parameters){

//實(shí)際實(shí)現(xiàn)...}抽象類派生類提供重寫方法原型必須重寫

抽象類和抽象方法

運(yùn)行時的多態(tài)性是通過繼承和虛成員來實(shí)現(xiàn)的。運(yùn)行時的多態(tài)性是指系統(tǒng)在編譯時不確定選用哪個重載方法,而是直到程序運(yùn)行時,才根據(jù)實(shí)際情況決定采用哪個重載方法。

編譯時的多態(tài)性具有運(yùn)行速度快的特點(diǎn),而運(yùn)行時的多態(tài)性則具有極大的靈活性。5.3操作符重載

這個方法允許用戶定義的類型例如結(jié)構(gòu)和類,為使它們的對象易于操作而使用重載操作符。如何實(shí)現(xiàn)操作符重載運(yùn)算符重載實(shí)質(zhì)上就是函數(shù)重載運(yùn)算符的函數(shù)表示法語法規(guī)定允許重載的運(yùn)算符:表如下必須是punlic和static至少有一個參數(shù)是類自身運(yùn)算符函數(shù)表示法opxoperatorop(x)xopoperatorop(x)xopyoperatorop(x,y)操作符描述+,-,!,~,++,--

這些一元操作符需要一個操作數(shù),可以被重載。+,-,*,/,%這些二元操作符需要兩個操作數(shù),可以被重載。==,!=,<,>,<=,>=比較操作符可以被重載。&&,||條件邏輯操作符不能被直接重載,但是它們使用&和|它們可以求值,被重載。+=,-=,*=,/=,%=賦值操作符不能被重載。=,.,?:,->,new,is,sizeof,typeof這些操作符不能被重載。

classTwoD{privateintx;publicintX{get{returnx;}}privateinty;publicintY{get{returny;}}publicTwoD(){x=y=0;}publicTwoD(inta,intb){x=a;y=b;

}publicstaticTwoDoperator+(TwoDop1,TwoDop2){TwoDjieguo=newTwoD();jieguo.x=op1.x+op2.x;jieguo.y=op1.y+op2.y;returnjieguo;}publicstaticTwoDoperator+(TwoDop1,intop2){TwoDjieguo=newTwoD();jieguo.x=op1.x+op2;jieguo.y=op1.y+op2;returnjieguo;}publicoverridestringToString(){returnstring.Format("x坐標(biāo):{0},y坐標(biāo):{1}",X,Y);

}

}

classThreeD:TwoD{privateintz;publicThreeD():base(){z=0;}publicThreeD(inta,intb,intc):base(a,b){z=c;}publicintZ{get{returnz;}}publicstaticThreeDoperator+(ThreeDop1,ThreeDop2){ThreeDjieguo=newThreeD(op1.X+op2.X,op1.Y+op2.Y,op1.z+op2.z);returnjieguo;}publicstaticThreeDoperator++(ThreeDop1){ThreeDjg=newThreeD(op1.X+1,op1.Y+1,op1.z+1);returnjg;}publicstaticbooloperator==(ThreeDop1,ThreeDop2){if((op1.X==op2.X)&&(op1.Y==op2.Y)&&(op1.z==op2.z))returntrue;elsereturnfalse;}publicstaticbooloperator!=(ThreeDop1,ThreeDop2){if((op1.X!=op2.X)||(op1.Y!=op2.Y)||(op1.z!=op2.z))returntrue;elsereturnfalse;}publicoverridestringToString(){returnstring.Format("{0},z坐標(biāo):{1}",base.ToString(),Z);

}

}操作符重載為C#操作符應(yīng)用到用戶定義的數(shù)據(jù)類型提供了額外的能力。僅預(yù)定義的C#操作符可以被重載。5.4結(jié)構(gòu)把一系列相關(guān)的變量組織成單一實(shí)體的過程,在C#中稱為生成結(jié)構(gòu)的過程。這個單一實(shí)體的類型就叫做結(jié)構(gòu)類型,每一個變量稱為結(jié)構(gòu)的成員。自定義數(shù)據(jù)類型可以在其內(nèi)部定義方法無法實(shí)現(xiàn)繼承屬于值類型主要結(jié)構(gòu):structstudent{ publicintstud_id; publicstringstud_name; publicdoublestud_marks; publicvoidshow_details() { //顯示學(xué)生詳細(xì)信息 }}結(jié)構(gòu)數(shù)據(jù)成員方法所有與Student關(guān)聯(lián)的詳細(xì)信息都可以作為一個整體進(jìn)行存儲和訪問classProgram{staticvoidMain(string[]args){studentst=newstudent(12,"irin",90.8);st.show_details();Console.ReadLine();}}structstudent{publicintstud_id;publicstringstud_name;publicdoublestud_marks;publicstudent(intid,stringname,doublemarks){stud_id=id;stud_name=name;stud_marks=marks;}publicvoidshow_details(){Console.WriteLine("id={0},name={1},marks={2}",stud_id,stud_name,stud_marks);}}5.5枚舉比如,聲明一個代表季節(jié)的枚舉類型的變量:enumSeason{Spring,Summer,Autumn,Winter};SeasoncurrentSeason;枚舉類型為一組在邏輯上密不可分的整數(shù)提供便于記憶的符號枚舉publicclassHoliday{publicenumWeekDays{ Monday, Tuesday, Wednesday, Thursday, Friday}publicvoidGetWeekDays(StringEmpName,WeekDaysDayOff){//處理工作日}staticvoidMain(){HolidaymyHoliday=newHoliday();myHoliday.GetWeekDays("Richie",Holiday.WeekDays.Wednesday);}}枚舉(Enum,Enumerator的縮寫)是一組已命名的數(shù)值常量

用于定義具有一組特定值的數(shù)據(jù)類型枚舉以enum關(guān)鍵字聲明Wednesday=2枚舉publicclassHoliday{publicenumWeekDays{Monday,Tuesday,Wednesday,Thursday,Friday}publicvoidGetWeekDays(StringEmpName,WeekDaysDayOff){Console.WriteLine("{0}isfreein{1}",EmpName,DayOff);}}枚舉classProgram{staticvoidMain(string[]args){Holidayhl=newHoliday();hl.GetWeekDays("irin",Holiday.WeekDays.Friday);Console.WriteLine("你可以休息的日期是在禮拜"+(int)Holiday.WeekDays.Friday);

Console.ReadLine();

}

}枚舉(續(xù))C#中的枚舉包含與值關(guān)聯(lián)的數(shù)字默認(rèn)情況下,將0值賦給枚舉的第一個元素,然后對每個后續(xù)的枚舉元素按1遞增在初始化過程中可重寫默認(rèn)值publicenumWeekDays{ Monday=1, Tuesday=2, Wednesday=3, Thursday=4, Friday=5}5.6接口OFFON請按開關(guān)按鈕:ON/OFF兩種方法ONOFF5.6接口OFFONISwitchON()OFF()

classProgram{staticvoidMain(string[]args){RadioSwitchrs=newRadioSwitch();rs.On();rs.Off();UpDownSwitchuds=newUpDownSwitch();uds.On();uds.Off();Console.ReadLine();}}publicinterfaceISwitch{voidOn();voidOff();}接口1接口1

publicclassRadioSwitch:ISwitch{publicvoidOn(){Console.WriteLine("順時針旋轉(zhuǎn)開啟!");}publicvoidOff(){Console.WriteLine("逆時針旋轉(zhuǎn)關(guān)閉!");}}publicclassUpDownSwitch:ISwitch{publicvoidOn(){Console.WriteLine("向上按開啟!");}publicvoidOff(){Console.WriteLine("向下按關(guān)閉!");}}輸出結(jié)果:如何實(shí)現(xiàn)接口基本步驟定義接口:接口定義了協(xié)定實(shí)現(xiàn)接口:類實(shí)現(xiàn)了接口的協(xié)定接口的定義接口是引用類型關(guān)鍵字interface接口的成員有:屬性、方法、事件和索引器接口中定義的成員只有聲明,沒有實(shí)現(xiàn)接口中的成員都隱式地具有public訪問屬性接口

classIBase{

voidmethod1();intmethod2();intmethod3(float);//沒有實(shí)現(xiàn)

…….}接口interface只有方法聲明沒有實(shí)現(xiàn)

classProgram{staticvoidMain(string[]args){MyPointmp=newMyPoint(11,12);Console.WriteLine("myX={0},myY={1}",mp.X,mp.Y);Console.ReadLine();}}interfaceIPoint{intX{get;set;}intY{get;set;}}

接口2

classMyPoint:IPoint{privateintmyX;privateintmyY;publicMyPoint(intx,inty){myX=x;myY=y;}//實(shí)現(xiàn)IPoint接口中的屬性publicintX{get{returnmyX;}set{myX=value;}}publicintY{get{returnmyY;}set{myY=value;}}}

接口2輸出結(jié)果:用類實(shí)現(xiàn)接口語法:與繼承一樣規(guī)定:必須實(shí)現(xiàn)接口中聲明的所有成員接口的繼承

classProgram{staticvoidMain(string[]args){Pp=newP();p.ParentFun();Cc=newC();c.ParentFun();c.ChildFun();Console.ReadLine();}}interfaceIParent{voidParentFun();}interfaceIChild:IParent{voidChildFun();}接口的繼承

classP:IParent{publicvoidParentFun(){Console.WriteLine("P類實(shí)現(xiàn)IParent接口的ParentFun()");

}

}

classC:IChild

{

publicvoidParentFun()

{

Console.WriteLine("C類實(shí)現(xiàn)IParent接口的ParentFun()");

}

publicvoidChildFun()

{

Console.WriteLine("C類實(shí)現(xiàn)IChild接口的ChildFun()");

}

}輸出結(jié)果:接口與繼承接口的繼承接口可以繼承接口可以從多個基接口繼承類的繼承、實(shí)現(xiàn)接口的類相同的語法:類的繼承,類實(shí)現(xiàn)接口類不能多重繼承類可以實(shí)現(xiàn)多個接口類不允許多重繼承規(guī)則:類的基列表中可以同時包含基類和接口,但基類應(yīng)列在首位C#可以通過接口來實(shí)現(xiàn)多重繼承接口與繼承

classProgram{staticvoidMain(string[]args){//實(shí)現(xiàn)接口IParent的類P

IParentiParent1=newP();

IParentiParent2=(IParent)(newP());

iParent1.ParentFun();

iParent2.ParentFun();

//實(shí)現(xiàn)接口IChild的類C,IChild接口從IParent接口繼承IParentiParent3=newC();IParentiParent4=(IParent)(newC());iParent3.ParentFun();iParent4.ParentFun();//編譯錯誤//IChildiChild1=newP();//運(yùn)行錯誤,拋出InvalidCastException異常//IChildiChild2=(IChild)(newP());IChildiChild3=newC();IChildiChild4=(IChild)(newC());iChild3.ChildFun();iChild3.ParentFun();iChild4.ChildFun();iChild4.ParentFun();Console.ReadLine();}}接口與繼承

interfaceIParent{voidParentFun();}interfaceIChild:IParent{voidChildFun();}classP:IParent{publicvoidParentFun(){Console.WriteLine("P類實(shí)現(xiàn)IParent接口的ParentFun()");

}

}

classC:IChild

{

publicvoidParentFun()

{

Console.WriteLine("C類實(shí)現(xiàn)IParent接口的ParentFun()");

}

publicvoidChildFun()

{

Console.WriteLine("C類實(shí)現(xiàn)IChild接口的ChildFun()");

}

}輸出結(jié)果:接口的實(shí)例什么是接口的實(shí)例接口類型的變量(不能用new實(shí)例化)聲明語法:接口類型

接口實(shí)例名接口實(shí)例的賦值從……中提取接口接口實(shí)例=對象名接口實(shí)例=(接口類型)對象名接口實(shí)例=(接口類型)接口實(shí)例A接口實(shí)例的作用通過接口實(shí)例訪問接口的成員編譯正確,可能發(fā)生運(yùn)行錯誤可能發(fā)生編譯錯誤接口3

classProgram{staticvoidMain(string[]args){//實(shí)現(xiàn)接口IParent的類P

IParentiParent=newP();

//運(yùn)行錯誤,拋出InvalidCastException異常//IChildiChild2=(IChild)(iParent);//實(shí)現(xiàn)接口IChild的類C,IChild接口從IParent接口繼承IParentiParent1=newC();iParent1.ParentFun();IChildiChild1=(IChild)(iParent1);iChild1.ChildFun();IChildiChild2=newC();iChild2.ChildFun();IParentiParent2=(IParent)iChild2;iParent2.ParentFun();Console.ReadLine();}}接口3

interfaceIParent{voidParentFun();}interfaceIChild:IParent{voidChildFun();}classP:IParent{publicvoidParentFun(){Console.WriteLine("P類實(shí)現(xiàn)IParent接口的ParentFun()");

}

}

classC:IChild

{

publicvoidParentFun()

{

Console.WriteLine("C類實(shí)現(xiàn)IParent接口的ParentFun()");

}

publicvoidChildFun()

{

Console.WriteLine("C類實(shí)現(xiàn)IChild接口的ChildFun()");

}

}輸出結(jié)果:接口的應(yīng)用用接口實(shí)現(xiàn)多重繼承用接口實(shí)現(xiàn)多態(tài)多重繼承:鴨子是一種鳥,會游泳,同時又是一種食物

classProgram{staticvoidMain(string[]args){Duckd=newDuck();d.Fly();d.Cook();d.Swim();Console.ReadLine();}}publicinterfaceISwim{voidSwim();}publicinterfaceIFood{voidCook();}publicabstractclassBird{publicabstractvoidFly();}

publicclassDuck:Bird,IFood,ISwim{publicoverridevoidFly(){Console.WriteLine("只有野鴨才會飛!");}publicvoidCook(){Console.WriteLine("北京烤鴨就是一道美食!");}publicvoidSwim(){Console.WriteLine("鴨子都會游泳!");}}輸出結(jié)果:接口多態(tài):小鳥,飛機(jī),熱氣球,風(fēng)箏都可以在天空飛classProgram{staticvoidMain(string[]args){IFly[]flys=newIFly[3];flys[0]=newBalloon();flys[1]=newKite();flys[2]=newPlane();foreach(IFlyfinflys){f.Fly();}Console.ReadLine();}}publicinterfaceIFly{voidFly();}

publicclassBalloon:IFly{publicvoidFly(){Console.WriteLine("Balloon升上天空!");}}publicclassKite:IFly{publicvoidFly(){Console.WriteLine("Kite在天空隨風(fēng)飄!");}}publicclassPlane:IFly{publicvoidFly(){Console.WriteLine("Plane在高空飛翔!");}}輸出結(jié)果:classProgram{staticvoidMain(string[]args){Carc=newCar();c.Start();Planep=newPlane();p.Start();p.fly();Console.ReadLine();}}abstractclassVehicle{publicabstractvoidStart();}interfaceIflyanle{voidfly();}抽象類classCar:Vehicle{publicoverridevoidStart(){Console.WriteLine("汽車起步");}}classPlane:Vehicle,Iflyanle{publicoverridevoidStart(){Console.WriteLine("飛機(jī)起飛");}publicvoidfly(){Console.WriteLine("我會飛!");}}輸出結(jié)果:抽象類與接口抽象類接口屬性、方法、事件和索引器可以只有聲明的方法,也可以有完整的方法方法都只有聲明是對實(shí)體的抽象是對行為的抽象規(guī)定行為的準(zhǔn)則子類與抽象類在概念上是一致的實(shí)現(xiàn)接口的類與接口在概念上是不同的多重接口實(shí)現(xiàn)C#不允許多重類繼承但C#允許多重接口實(shí)現(xiàn)

這意味著一個類可以實(shí)現(xiàn)多個接口

classProgram{staticvoidMain(string[]args){Aa=newA();a.Print();Bb=newB();b.Print();Console.ReadLine();}}interfaceIPoint{voidPrint();}接口繼承classA:IPoint{publicvoidPrint(){Console.WriteLine("Yes");}}classB:IPoint{publicvoidPrint(){Console.WriteLine("No");}}輸出結(jié)果:顯式接口實(shí)現(xiàn)在C#中,只要不發(fā)生命名沖突,就完全可以允許多重接口實(shí)現(xiàn)publicinterfaceIPictManip{ voidApplyAlpha();}publicinterfaceIPict{ voidApplyAlpha();}publicclassMyImages:BaseIO,IPict,IPictManip{ publicintApplyAlpha() { ....... ....... }}?使用顯式接口實(shí)現(xiàn)演示:示例12publicclassMyImages:BaseIO,IPict,IPictManip{publicintDeleteImage(){ Console.WriteLine(“DeleteImage實(shí)現(xiàn)!");

return(5);

}

publicvoidApplyAlpha()

{

Console.WriteLine(“ApplyAlpha實(shí)現(xiàn)!");

}

voidIPict.DisplayImage(){

Console.WriteLine(“DisplayImage的IPict實(shí)現(xiàn)");

}

voidIPictManip.DisplayImage(){ Console.WriteLine(“DisplayImage的IPictManip實(shí)現(xiàn)");

}}顯式接口實(shí)現(xiàn)classProgram{staticvoidMain(string[]args){MyImagesobjM=newMyImages();IPictPict=objM;//IPict引用Pict.DisplayImage();IPictManipPictManip=objM;//IPictManip引用PictManip.DisplayImage();

}}publicinterfaceIPict{intDeleteImage();voidDisplayImage();}publicinterfaceIPictManip{voidDisplayImage();}publicinterfaceBaseIO{voidApplyAlpha();}輸出結(jié)果:classProgram{staticvoidMain(string[]args){MyImagesobjM=newMyImages();objM.DisplayImage();intval=objM.DeleteImage();Console.WriteLine(val);objM.ApplyAlpha();

objM.ApplyBeta();Console.ReadLine();}}publicinterfaceIPict{intDeleteImage();}publicinterfaceIPictManip{voidApplyAlpha();voidDisplayImage();}//繼承多重接口publicinterfaceIPictAll:IPict,IPictManip{voidApplyBeta();}非顯示接口實(shí)現(xiàn)

publicclassMyImages:IPictAll{publicintDeleteImage(){Console.WriteLine("DeleteImage實(shí)現(xiàn)!");return(5);}publicvoidApplyAlpha(){Console.WriteLine("ApplyAlpha實(shí)現(xiàn)!");}publicvoidApplyBeta(){Console.WriteLine("ApplyBeta實(shí)現(xiàn)!");}publicvoidDisplayImage(){Console.WriteLine("DisplayImage實(shí)現(xiàn)!");}}輸出結(jié)果:publicdelegateintFirstDelegate(intx,inty);classMyMath{ publicintAdd(intx,inty) { returnx+y;

}}MyMathmath=newMyMath();FirstDelegated=math.Add;Console.WriteLine(d(20,30));委托FirstDelegate代表一類函數(shù),該類函數(shù)的原型是:兩個整型參數(shù),并且返回整型可以把委托變量d當(dāng)成函數(shù)一樣使用輸出結(jié)果:5.7委托的概念古代的時候大多是人都是通過相親,成為夫妻的。而在他們相親的時候,都是通過媒婆介紹認(rèn)識的。這時候男女雙方要求什么條件都是通過媒婆來傳達(dá)的。而這個媒婆就類似于委托。生活例子:5.7委托的概念委托(delegate)也是一種數(shù)據(jù)類型,它指的是某種類型的方法可以定義委托變量(委托對象),但該變量接收的是一個函數(shù)的地址5.7使用委托委托是從System.Delegate派生的類使用委托的步驟定義一個新的委托聲明委托變量并實(shí)例化使用委托變量通過委托變量調(diào)用方法委托變量可以作為參數(shù)傳遞定義一個新的委托語法位置[訪問修飾符]delegate

返回類型委托名(參數(shù)列表);

聲明委托變量并實(shí)例化語法符合委托MyDelegate要求的方法??梢允菍?shí)例方法,也可以是靜態(tài)方法。MyMathmath=newMyMath();FirstDelegated=math.Add;Console.WriteLine(d(20,30));把符合委托要求的方法直接賦值給委托變量符合委托要求:返回值、方法簽名要一致通過委托變量調(diào)用方法1

classProgram{staticvoidMain(string[]args){MyDelegated=newMyDelegate(MyClass.Square);d(2);Console.ReadLine();}}delegatevoidMyDelegate(floatx);classMyClass{publicstaticvoidSquare(floatx){floatresult=x*x;Console.WriteLine("{0}的平方等于:{1}",x,result);

Cons

溫馨提示

  • 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)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論