编程中的物件与类别100_第1页
编程中的物件与类别100_第2页
编程中的物件与类别100_第3页
编程中的物件与类别100_第4页
编程中的物件与类别100_第5页
已阅读5页,还剩100页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1编程中的物件与类别2封装(Encapsulation)类别将状态变量与功能函式封装起来通常状态变量为私有(private),只供同类别之功能函式取用,不可以由类别外直接取用避开同名变量问题避免被不慎改动,破坏状态的正确一致性容易维护,不影响外界程序功能函式可能公用(public),也可能私有一类别至少有一公用函式,以便应用3类别Dice4新增类别程序项目>加入类别>类别输入类别名称.cs5DiceSimulation.Program片段Dicedice=newDice();dice.Toss();

Console.WriteLine("掷出"+dice.FaceValue);

6DiceSimulation.Dice片段publicclassDice{

intfaceValue=1;Randomrand=newRandom();publicintFaceValue

{get{returnfaceValue;}set{faceValue=value;}}

publicvoidToss()

{faceValue=rand.Next()%6+1;

}}

7程序(Procedure)呼叫*J.G.Brookshear,ComputerScience–AnOverview,8thedition,Addison-Wesley,20058函式呼叫流程dice.Toss();staticvoidMain(string[]args){

}publicclassDice{...

publicvoidToss()

{faceValue=rand.Next()%6+1;

}...}publicclassRandom{...

publicint

Next()

{...

}...}9资料型别实值型别(ValueType)结构(Structs)数值(Numeric)布林(bool)使用者定义Structs列举(Enumerations)参考型别(ReferenceType)字符串(string)物件(object)10堆栈(Stack)与堆积(Heap)StackHeap...11实值型别储存方式堆栈(Stack)intx=100;100x12参考型别储存方式堆栈(Stack)stringx=“abc”;x参考‘a’‘b’‘c’堆积(Heap)13物件(Object)观念dice1存储器地址1dice2存储器地址2dice1.faceValuedice2.faceValue函式成员Toss进入点函式Toss进入地址dice1.rand函式Toss进入地址dice2.rand14物件的设定(Assignment)dice2=dice1;dice1存储器地址1dice2存储器地址2dice1.faceValuedice2.faceValue函式成员Toss进入点函式Toss进入地址dice1.rand函式Toss进入地址dice2.rand15存取修饰词

public

private

protected

internal16侦错器的进一步应用“逐步执行”与”不进入函式”的差别目前类别与函式显示监看式的应用呼叫堆栈的应用实时运算视窗的应用17练习宣告并测试以下类别18测试软件错误代价可能极为高昂测试可以发现并改正程序错误通过的测试越多,程序越可靠19测试时机与风险20极端化程序设计

(ExtremeProgramming)撰写一个简单的测试程序编译执行程序,看它失败增添恰能通过测试之程序码并编译侦错重整及消除冗余程序码并编译侦错反覆进行上述步骤21测试驱动开发方式

(Test-DrivenDevelopment-TDD)写测试主程序,呼叫测试函式,建置,看它失败写测试类别,加上测试函式,重新建置,看它失败撰写欲测试的类别,加上株段(stub)函式,使通过建置,但不通过测试改写株段函式,通过建置与测试以相同方式,增加新测试22TDD参考资料P.Provost,“Test-drivendevelopmentin.NET,”/KB/dotnet/tdd_in_dotnet.aspx23类别Card24测试规画

♠A

♥J

♦10

♣325程序TestingCard.Program.csusingSystem;usingSystem.Diagnostics;namespaceTestingCard{classProgram{staticvoidMain(string[]args){CardTesttest=newCardTest();Debug.Assert(test.Spade_A_OK());}}}26程序TestingCard.CardTest.csusingSystem;namespaceTestingCard{classCardTest{publicboolSpade_A_OK(){Cardcard=newCard();card.Suit='s';card.Rank=1;return(card.Suit=='s'&&

card.Rank==1);}}}27程序TestingCard.Card.csusingSystem;namespaceTestingCard

{publicclassCard

{

privatecharsuit;

privateintrank;

publiccharSuit

{

get{returnsuit;}

set{suit=value;}

}

publicintRank

{

get{returnrank;}

set{rank=value;}}}}28练习完成类别Card的其他三个测试29练习重新以TDD测试类别Car30CalculatorTest.Program片段Calculatorcalculator=newCalculator();Console.Write("输入第一个数字:");operand1=int.Parse(Console.ReadLine());Console.Write("输入第二个数字:");operand2=int.Parse(Console.ReadLine());result=calculator.Add(operand1,operand2);Console.WriteLine("{0}+{1}={2}",operand1,operand2,result);31CalculatorTest.Calculator片段publicclassCalculator{publicintAdd(inta,intb)

{intresult=a+b;returnresult;}

publicintSubtract(inta,intb)

{intresult=a-b;returnresult;}...}

32程序参数与区域变量模块(Module)观念程序码重覆使用程序共同开发资料独立参数(Parameters,或称自变量Arguments)形式参数(FormalParameters)真实参数(ActualParameters)区域变量(Localvariables)33数学函数呼叫流程doubley=Math.Sqrt(2.0);classMath{staticdoubleSqrt(doublex){

...returnresult;}}34记忆配置结果变量传回值真实参数形式参数区域变量呼叫模块记忆区被呼叫模块记忆区区域变量35函式传回值Program.Main()resultcalculator.Add()resultreturnvalue36练习设定operand值并利用Assert叙述改写CalculatorTest程序37SwappingIntegers.Program片段intx=3;inty=5;Swap(refx,refy);Debug.Assert(x==5&&y==3);...

staticvoidSwap(refintx,refinty){inttemp=x;x=y;y=temp;}38PassByReferenceAndOut.Program片段(1/2)doublelength=100.0;Squares=newSquare();s.Side=length;doublearea1=0.0;doubleperimeter1=0.0;s.GetAreaAndPerimeter(refarea1,

refperimeter1);Console.WriteLine(

"正方形边长:{0},面积:{1},周长:{2}",

length,area1,perimeter1);39PassByReferenceAndOut.Program片段(2/2)doublearea2;doubleperimeter2;s.GetAreaAndPerimeterUsingOut(outarea2,

outperimeter2);Console.WriteLine(

"正方形边长:{0},面积:{1},周长:{2}",

length,area2,perimeter2);40PassByReferenceAndOut.Square片段publicvoidGetAreaAndPerimeter(

refdoublearea,refdoubleperimeter){area=Math.Pow(a,2);perimeter=4.0*a;}publicvoidGetAreaAndPerimeterUsingOut(

outdoublearea,outdoubleperimeter){area=Math.Pow(a,2);perimeter=4.0*a;}41传值,传址,out参数传值参数传递(Passbyvalue)传址参数传递(Passbyreference)out参数初值设定问题42练习(1/3)写主程序Program.Main()利用之前的Card类别,宣告两张扑克牌Card物件呼叫Program中的static函数Swap()交换两张牌位置以传值参数参照下一页虚拟码,写一个函式Program.Swap()交换两张牌位置43练习(2/3)函式Swap虚拟码ProcedureSwap(card1,card2)1.temp=card1;2.card1=card2;3.card2=temp;returncard1card2temp44练习(3/3)将Swap函式之参数设为传值参数用Assert叙述测试两张牌能否交换将Swap函式之参数改为传址参数,再试一次利用侦错器找出结果差异之原因45OverloadingDemo.Program片段Adderadder=newAdder();inta=3;intb=5;Debug.Assert(adder.Add(a,b)==8);doublead=3.2;doublebd=5.1;Debug.Assert(adder.Add(ad,bd)==8.3);46OverloadingDemo.Adder片段publicintAdd(inta,intb){

return(a+b);}publicdoubleAdd(doublea,doubleb){return(a+b);}47DiceSimulation2.Program片段intseed=123;Dicedice=newDice(seed);dice.Toss();Console.WriteLine("掷出"+

dice.FaceValue);

48DiceSimulation2.Dice片段publicDice(){rand=newRandom();

Toss();}publicDice(intseed){rand=newRandom(seed);Toss();}

49建构函式与解构函式

(ConstructorandDestructor)预设建构函式(defaultconstructor)具参数之建构函式检验参数范围解构函式50物件产生与消灭流程staticvoidmain(string[]arg){Dicedice=newDice(seed);publicDice(intseed){...}}~Dice(){...}删除物件dice离开主函式,程序结束物件宣告物件生成51练习修改类别Card,改用建构函式设定初值,以属性取得suit及rank52UsingThis.Program片段Timet=newTime(11,30,52);inthour;intmin;intsec;t.GetTime(outhour,outmin,

outsec);Console.WriteLine(

"现在时间{0}:{1}:{2}",hour,min,sec);53UsingThis.Time片段publicTime(inthour,intmin,intsec){

boolparamsAreValid=hour>=0&&hour<24&&min>=0&&min<60&&sec>=0&&sec<60;

if(paramsAreValid)

{this.hour=hour;this.min=min;this.sec=sec;}else{Console.WriteLine("Time建构式参数值不合理");}

}54物件自我参考thist存储器地址函式成员GetTime进入点GetTime()进入地址thishourminsec55类别TimeConversion56UsingStatic.Program片段inthoursToMins=

TimeConversion.HoursToMins(hours);intdaysToHours=

TimeConversion.DaysToHours(days);Console.WriteLine(hours+"hours="+

hoursToMins+"minutes");Console.WriteLine(days+"days="+

daysToHours+"hours");Testt1=newTest();Testt2=newTest();Console.WriteLine(Test.GetNConstructed+

"Testobjectswereconstructed");57UsingStatic.TimeConversion片段publicstaticclassTimeConversion{privateconstintHOURS_PER_DAY=24;privateconstintMINS_PER_HOUR=60;

publicstaticintHoursToMins(inthours)

{

returnhours*MINS_PER_HOUR;

}publicstaticintDaysToHours(intdays){

returndays*HOURS_PER_DAY;}}58UsingStatic.Test片段publicclassTest{privatestaticintnConstructed=0;publicTest()

{++nConstructed;}publicstaticintGetNConstructed

{get

{

returnnConstructed;

}}}59静态成员与静态类别常数宣告静态成员应用场合静态函式Main静态类别应用场合60静态成员的记忆配置t1存储器地址1t2存储器地址2函式成员Test进入点函式Test()进入地址函式Test()进入地址nConstructedTest函式成员GetNConstructed进入点存储器地址61练习(1/2)在类别Card内增加静态成员函式,累计产生的Card物件数写一程序利用类别Card产生三张扑克牌,放在deck内,印出产生的牌数62练习(2/2)实作并测试一静态类别EqSolver,内含两静态成员函式doubleLinear(doublea,doubleb)及doubleQuadratic(doublea,doubleb,doublec)分别解一次方程式ax+b=0及ax2+bx+c=063UsingStruct.Program片段(1/2)structPoint2D{publicintx;publicinty;}64UsingStruct.Program片段(2/2)staticvoidMain(string[]args){Point2Dpt=newPoint2D();Console.WriteLine(

"Initiallocation=({0},{1})",pt.x,pt.y);pt.x=3;pt.y=4;Console.WriteLine(

"Finallocation=({0},{1})",pt.x,pt.y);}65StructVSClass.SPoint2D片段structSPoint2D{publicintx;publicinty;

publicSPoint2D(intx,inty){this.x=x;this.y=y;}}

66StructVSClass.CPoint2D片段classCPoint2D{publicintx;publicinty;publicCPoint2D(){x=0;y=0;}publicCPoint2D(intx,inty){this.x=x;this.y=y;}}67StructVSClass.Program片段(1/4)SPoint2DsPt1=newSPoint2D(3,4);SPoint2DsPt2=newSPoint2D();SPoint2DsPt3=newSPoint2D();sPt2=sPt1;sPt3=sPt1;Console.WriteLine("sPt1=({0},{1})",

sPt1.x,sPt1.y);Console.WriteLine("sPt2=({0},{1})",

sPt2.x,sPt2.y);Console.WriteLine("sPt3=({0},{1})",

sPt3.x,sPt3.y);

68StructVSClass.Program片段(2/4)CPoint2DcPt1=newCPoint2D(3,4);CPoint2DcPt2=newCPoint2D();CPoint2DcPt3=newCPoint2D();

cPt2=cPt1;cPt3=cPt1;Console.WriteLine("cPt1=({0},{1})",

cPt1.x,cPt1.y);Console.WriteLine("cPt2=({0},{1})",

cPt2.x,cPt2.y);Console.WriteLine("cPt3=({0},{1})",

cPt3.x,cPt3.y);

69StructVSClass.Program片段(3/4)sPt1.x=10;sPt1.y=20;sPt2.x=30;sPt2.y=40;Console.WriteLine("sPt1=({0},{1})",

sPt1.x,sPt1.y);Console.WriteLine("sPt2=({0},{1})",

sPt2.x,sPt2.y);Console.WriteLine("sPt3=({0},{1})",

sPt3.x,sPt3.y);

70StructVSClass.Program片段(4/4)cPt1.x=10;cPt1.y=20;cPt2.x=30;cPt2.y=40;Console.WriteLine("cPt1=({0},{1})",

cPt1.x,cPt1.y);Console.WriteLine("cPt2=({0},{1})",

cPt2.x,cPt2.y);Console.WriteLine("cPt3=({0},{1})",

cPt3.x,cPt3.y);

71结构定义方式与类别相似记忆配置于堆栈适合使用于小型资料集合减少记忆回收之负担不可自订预设建构函式成员变量不能直接设定初值设值时直接复制资料成员内容不支援继承功能72类别物件记忆配置cPt1存储器地址1cPt2存储器地址2cPt1.xcPt2.xcPt1.ycPt2.yheapspacecPt2=cPt1;73结构物件记忆配置sPt1sPt2sPt1.xsPt2.xsPt1.ysPt2.ystack74练习宣告并测试结构Student,其中包括学号、姓名、成绩75UsingCopyConstructor.CPoint2D片段publicCPoint2D(){x=0;y=0;}publicCPoint2D(intx,inty){this.x=x;this.y=y;}publicCPoint2D(CPoint2Dp){x=p.x;y=p.y;}76UsingCopyConstructor.Program片段(1/2)CPoint2DcPt1=newCPoint2D(3,4);CPoint2DcPt2=newCPoint2D(cPt1);CPoint2DcPt3=newCPoint2D(cPt1);Console.WriteLine("cPt1=({0},{1})",

cPt1.x,cPt1.y);Console.WriteLine("cPt2=({0},{1})",

cPt2.x,cPt2.y);Console.WriteLine("cPt3=({0},{1})",

cPt3.x,cPt3.y);

77UsingCopyConstructor.Program片段(2/2)cPt1.x=10;cPt1.y=20;cPt2.x=30;cPt2.y=40;Console.WriteLine("cPt1=({0},{1})",

cPt1.x,cPt1.y);Console.WriteLine("cPt2=({0},{1})",

cPt2.x,cPt2.y);Console.WriteLine("cPt3=({0},{1})",

cPt3.x,cPt3.y);78浅层复制与深层复制浅层复制(Shallowcopy)系统提供只复制参考(Reference)地址没有新物件产生深层复制(Deepcopy)程序师提供产生新物件应复制所有资料成员79练习宣告并测试类别Student,其中包括学号、姓名、成绩,仿照程序StructVSClass及UsingCopyConstructor分别使用设值与复制建构函式产生Student物件,观察浅层复制与深层复制的差别80株段函式(StubFunctions)与

混充类别(MockClasses)初期测试用以确认呼叫方式正确多数程序错误发生于函式呼叫易写易建立执行快速产生确定结果易确认呼叫方式正确81BlackJack_0_0_0.ProgramusingSystem;usingSystem.Diagnostics;namespaceBlackJack_0_0_0{classProgram{staticvoidMain(string[]args){Debug.Assert(

BlackJackTest.Scenario_1_OK());}}}82混充类别BlackJack_0_0_0.BlackJackTestusingSystem;namespaceBlackJack_0_0_0{classBlackJackTest{publicstaticboolScenario_1_OK(){returntrue;}}}83项目与方案项目(Project)一个完整的应用程序或程序库方案(Solution)集合几个项目的问题解决方案84二十一点游戏模拟原型方案规画方案:BlackJack_0_0_1项目:BlackJack_0_0_1Program,BlackJackTest,Deck,HumanPlayer,ComputerPlayer,Hand,Card项目:TestingCard2Program,CardTest85BlackJack_0_0_1.Card片段(1/2)publicenumSuit{CLUB=0,DIAMOND=1,HEART=2,SPADE=3}86BlackJack_0_0_1.Card片段(2/2)publicstructCard{publicSuitsuit;publicintrank;publicCard(Suitsuit,intrank){this.suit=suit;this.rank=rank;}}87新增项目TestingCard2方案总管>(方案BlackJack_0_0_1)右键>加入>新增项目>储存现有项目>项目命名(TestingCard2)方案总管>(项目TestingCard2)参考>右键>加入参考>项目>(BlackJack_0_0_1)撰写主程序TestingCard2.Program建立并实作类别CardTest建置项目TestingCard2设定项目TestingCard2为启始项目开始侦错88TestingCard2.ProgramusingSystem;usingSystem.Diagnostics;namespaceTestingCard2{classProgram{staticvoidMain(string[]args){

Debug.Assert(CardTest.Spade_A_OK());}}}89TestingCard2.CardTestusingSystem;usingBlackJack_0_0_1;namespaceTestingCard2{classCardTest{publicstaticboolSpade_A_OK(){Cardcard=newCard(Suit.SPADE,1);return(card.suit==Suit.SPADE&&

card.rank==1);}}}90二十一点游戏模拟v0.1流程产生牌叠计算机(庄家)向玩家(一人)及本身派发一张明牌

计算机向玩家及本身派发一张明牌

庄家询问玩家是否加牌,直至玩家不加牌或报到庄家如不足17点便需加牌直至超过或等于17点

对未有爆煲或报到的玩家,比点数大小,大者胜,如庄家爆煲,玩家胜91二十一点游戏模拟原型之测试规画:

场景1玩家庄家♠A♥J♦10胜9292UML类别图(ClassDiagram)93Scenario1:SequenceDiagram94StepwiseRefinement算法设计Magicnumber7加减2逐层分解工作各项工作依繁简、重复性、可替代性决定是否写为函式95IsBlackJack()结构图(StructureChart)IsBlackJack()无A时判断有A时判断计算各牌点数Points()96追求简单清楚的程序选用简单有效的算法选用简单易修改的程序架构消除多余程序97BlackJack_0_0_1.ProgramusingSystem;usingSystem.Diagnostics;namespaceBlackJack_0_0_1{classProgram{staticvoidMain(string[]args){Debug.Assert(

BlackJackTest.Scenario_1_OK());}}}98BlackJack_0_0_1.BlackJackTest片段publicstaticboolScenario_1_OK(){Deckdeck=newDeck();HumanPlayerplayer=newHumanPlayer();

ComputerPlayercomputer=new

ComputerPlayer();player.SaveACard(deck.DealACard());

computer.SaveACard(deck.DealACard());player.SaveACard(deck.DealACard());return(player.IsBlackJack());}99BlackJack_0_0_1.Deck片段(1/2)privateCardcard1;p

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论