c#入门经典详解.pdf

上传人:无*** 文档编号:90899727 上传时间:2023-05-18 格式:PDF 页数:78 大小:8.02MB
返回 下载 相关 举报
c#入门经典详解.pdf_第1页
第1页 / 共78页
c#入门经典详解.pdf_第2页
第2页 / 共78页
点击查看更多>>
资源描述

《c#入门经典详解.pdf》由会员分享,可在线阅读,更多相关《c#入门经典详解.pdf(78页珍藏版)》请在得力文库 - 分享文档赚钱的网站上搜索。

1、问题解答Chapter 1:Introducing C#No exercises.Chapter 2:Writing a C#ProgramNo exercises.Chapter 3:Variables and ExpressionsExercise 1Q.In the following code,how would you refer to the name great from code in the namespacefab u lo u s?namespace fabulous(/code in fabulous namespace)namespace super(namespac

2、e smashing/great name definedA.super.sm ashing.greatExercise 2Q.Which of the following is not a legal variable name?a.m yV ariablelsG oodb.99Flakec._ f lo o rd tim e2G etJiggy W id lte A.b.Because it starts with a number,and,e Because it contains a full stop.Exercise 3Q.Is the string s u p e r c a l

3、if r a g i li s ti c e x p ia l id o c i o u s too big to fit in a s t r in gvariable?Why?A.No,there is no theoretical limit to the size of a string that may be contained in a strin g variable.Exercise 4Q.By considering operator precedence,list the steps involved in the computation of the followinge

4、xpression:resu ltV ar+=v a rl*var2+var3%var4/var5;A.The 木 and/operators have the highest precedence here,followed by+,%,and finally+=.Theprecedence in the exercise can be illustrated using parentheses as follows:resu ltV ar+=(v arl*var2)+var3)%(var4/v ar5);Exercise 5Q.Write a console application tha

5、t obtains four in t values from the user and displays their product.A.s ta tic void M ain(strin g args)(in t firstN um ber,secondNumber,thirdNumber,fourthNumber;C onsole.W riteLine(G ive me a number:0);firstN um ber=C onvert.Tolnt32(C onsole.R eadLine();C onsole.W riteLine(Give me another number:);s

6、econdNumber=C onvert.T oInt32(Console.ReadLine();C onsole.W riteL ine(nGive me another number:H;thirdNumber=C onvert.T olnt32(Console.ReadLine();C onsole.W riteLine(G ive me another number:);fourthNumber=C onvert.T oInt32(Console.ReadLine();C onsole.W riteLine(The product of 0,1,2,and 3 is 4.n,first

7、N um ber,secondNumber,thirdNumber,fourthNumber,firstN um ber*secondNumber*thirdNumber*fourthNumber);)Note that C o n v e rt.T o ln t3 2 ()is used here,which isnt covered in the chapter.Chapter 4:Flow ControlExercise 1Q.If you have two integers stored in variables v a r l and v a r2,what Boolean test

8、 can you performto see if one or the other(but not both)is greater than 10?A.(v a r l 1 0)人(v ar2 10)Exercise 2Q.Write an application that includes the logic from Exercise 1,obtains two numbers from the user,and displays them,but rejects any input where both numbers are greater than 10 and asks for

9、twonew numbers.A.s ta tic void M ain(strin g args)bool numbersOK=false;double varl,var2;varl=0;var2=0;while(!numbersOK)(Console.WriteLine(Give me a number:);varl=Convert.ToDouble(Console.ReadLine();Console.WriteLine(Give me another number:);var2=Convert.ToDouble(Console.ReadLine();if(varl 10)A(var2

10、10)(numbersOK=true;else(if(varl=10)&(var2 10)&(var2 10)(Console.WriteLine(Only one number may be greater than 10.”);elseInumbersOK=true;Console.WriteLine(You entered 0 and 1.,varl,var2);Exercise 3Q.What is wrong with the following code?int i;for(i=1;i=10;i+)if(i%2)=0)continue;Console.WriteLine(i);Th

11、e code should read:intfori;(i=1;i=imagMax;imagCoord+=imagStep)for(realCoord=realMin;realCoord=realMax;realCoord+=realStep)(iterations=0;realTemp=realCoord;imagTemp=imagCoord;arg=(realCoord*realCoord)+(imagCoord*imagCoord);while(arg 4)&(iterations=-1.2;coord.imag-=0.05)(for(coord.real=-0.6;coord.real

12、=1.77;coord.real+=0.03)(iterations=0;temp.real=coord.real;temp.imag=coord.imag;arg=(coord.real*coord.real)+(coord.imag*coord.imag);while(arg 4)&(iterations=0;index一)(reve rsedSt ring+=myStringindex;Console.WriteLine(Reversed:0z reversedString);Exercise 6Q.Write a console application that accepts a s

13、tring and replaces all occurrences of the string no withyes.A.static void Main(string args)(Console.WriteLine(nEnter a string:n);string myString=Console.ReadLine();myString=myString.Replace(Hno,yes”);Console.WriteLine(Replaced nno with nyesM:0”,myString);Exercise 7Q.Write a console application that

14、places double Quotes around each word in a string.static void Main(string args)Console.WriteLine(nEnter a string:n);string myString=Console.ReadLine();myString=nHn+myString.Replace(,H M H)+nH n;Console.WriteLine(Added double quotes areound words:0”,myString);Or using String.Split():static void Main(

15、string args)(Console.WriteLine(Enter a string:n);string myString=Console.ReadLine();string myWords=myString.Split();Console.WriteLine(Adding double quotes areound words:H);foreach(string myWord in myWords)(Console.Write(n0n”,myWord);Chapter 6:FunctionsExercise 1Q.The following two functions have err

16、ors.What are they?static bool Write()(Console.WriteLine(Text output from function.);static void myFunction(string label,params int args,bool showLabel)(if(showLabel)Console.WriteLine(label);foreach(int i in args)Console.WriteLine(0n,i);A.The first function has a return type of bool,but doesnt return

17、 a bool value.The second function has aparam s argument,but it isnt at the end of the argument list.Exercise 2Q.Write an application that uses two command line arguments to place values into a string and aninteger variable respectively,then display these values.A.static void Main(string args)(if(arg

18、s.Length!=2)(Console.WriteLine(Two arguments required.);return;)string paraml=args0;int param2=Convert.Tolnt32(args1);Console.WriteLine(String parameter:0”,paraml);Console.WriteLine(nInteger parameter:0“,param2);Note that this answer contains code that checks that 2 arguments have been supplied,whic

19、hwasnt part of the Question but seems logical in this situation.Exercise 3Q.Create a delegate and use it to impersonate the Console.ReadLine()function when askingfor user input.A.class Program|delegate string ReadLineDelegate();static void Main(string args)(ReadLineDelegate readLine=new ReadLineDele

20、gate(Console.ReadLine);Console.WriteLine(Type a string:n);string userinput=readLine();Console.WriteLine(nYou typed:0“,userInput);Exercise 4Q.Modify the following struct to include a function that returns the total price of an order:struct orderpublic stringpublic intpublic doublestruct orderpublic s

21、tringpublic intpublic doubleitemName;unitcount;unitCost;itemName;unitCount;unitCost;public double TotalCost()(return unitCount*unitCost;Exercise 5Q.Add another function to the order struct that returns a formatted string as follows,where italicentries enclosed in angle brackets are replaced by appro

22、priate values:Order Information:items at$each,totalcost$s tru c t orderpublic s trin g itemName;public in t unitC ount;public double u n itc o st;public double T otalC ost()(retu rn unitC ount*unitC ost;public s trin g Info()(retu rn nOrder inform ation:+unitC ount.T oS tring()+”+itemName+n item s a

23、 t$H+u n itc o st.T o S trin g()+n each,to ta l co st$”+TotalC ost().T oString();|)Chapter 7:Debugging and Error HandlingExercise 1Q.t4Using T race.W rite L in e ()is preferable to using D ebug.W rite L in e ()because theDebug version only works in debug buildsZ,Do you agree with this statement?Why?

24、A.This statement is only true for information that you want to make available in all builds.Moreoften,you will want debugging information to be written out only when debug builds are used.Inthis situation,the D ebug.W rite L in e ()version is preferable.Using the Debug.W rite L in e ()version also h

25、as the advantage that it will not be compiled intorelease builds,thus reducing the size of the resultant code.Exercise 2Q.Provide code for a simple application containing a loop that generates an error after 5000 cycles.Use a breakpoint to enter Break mode just before the error is caused on the 5000

26、th cycle.(Note:asimple way to generate an error is to attempt to access a nonexistent array element,such asm yA rray 1000 in an array with a hundred elements.)A.s ta tic void M ain(strin g args)(fo r(in t i=1;i 10000;i+)(Console.W riteLine(Loop cycle 0,i);i f (i=5000)(C onsole.W riteL ine(args999);I

27、n VS,a breakpoint could be placed on the following line:C onsole.W riteLine(nLoop cycle 0”,i);The properties of the breakpoint should be modified such that the hit count criterion is“breakwhen hit count is equal to 5000.In VCE,a breakpoint could be placed on the line that causes the error because yo

28、u cannot modifythe properties of breakpoints in VCE in this way.Exercise 3Q.f in a l ly code blocks execute only if a c a tc h block isnt executed.True or false?A.False,f i n a l l y blocks always execute.This may occur after a c a t ch block has been processed.Exercise 4Q.Given the enumeration data

29、 type o r i e n ta t io n defined in the following code,write anapplication that uses Structured Exception Handling(SEH)to cast a byte type variable into ano r i e n ta t io n type variable in a safe way.(Note:you can force exceptions to be thrown usingthe c h eck ed keyword,an example of which is s

30、hown here.This code should be used in yourapplication.)enum o rie n ta tio n :byte(north=1,south=2,e a st=3,west=4)myDirection=checked(orientation)m yB yte);A.s ta tic void M ain(strin g args)(o rie n ta tio n m yD irection;fo r(byte myByte=2;myByte 10;myByte+)(try(m yD irection=checked(orientation)

31、m yB yte);i f (myDirection o rie n ta tio n.w e st)throw new ArgumentOutOfRangeException(myByte,myByte,Value must be between 1 and 4);)catch(ArgumentOutOfRangeException e)(/I f th is sectio n is reached then myByte 4.C onsole.W riteLine(e.M essage);C onsole.W riteLine(A ssigning d e fa u lt value,o

32、rie n ta tio n.n o rth.);m yD irection=o rie n ta tio n.n o rth;C onsole.W riteLine(m yD irection=0n,m yD irection);This is a bit of a trick question.Because the enumeration is based on the byte type any bytevalue may be assigned to it,even if that value isnt assigned a name in the enumeration.In th

33、iscode you generate your own exception if necessary.Chapter 8:Introduction to Object-Oriented ProgrammingExercise 1Q.Which of the following are real levels of accessibility in OOP?a.Friendb.Publicc.Secured.Privatee.Protectedf.Looseg.WildcardA.(b)public,(d)private,and(e)protected are real levels of a

34、ccessibility.Exercise 2Q.You must call the destructor of an object manually,or it will waste memory.True or False?A.False.You should never call the destructor of an object manually.The.NET runtime environmentdoes this for you during garbage collection.Exercise 3Q.Do you need to create an object to c

35、all a static method of its class?A.No,you can call static methods without any class instances.Exercise 4Q.Draw a UML diagram similar to the ones shown in this chapter for the following classes andinterface:*An abstract class called HotDrink that has the methods Drink(),AddMilk(),andAddSugar(),and th

36、e properties Milk,and Sugar.*An interface called I Cup that has the methods Re f i 11(and Wash(),and theproperties C olor and Volume.*A class called CupOfCof fee that derives from HotDrink,supports the iCup interface,and has the additional property BeanType.*A class called CupOfTea that derives from

37、 HotDrink,supports the 工Cup interface,andhas the additional property LeafType.A.fg AA01.xxxExercise 5Q.Write some code for a fijnction that would accept either of the two cup objects in the aboveexample as a parameter.The function should call the AddMilk(),Drink(),and Wash()methods for and cup objec

38、t it is passed.A.static void ManipulateDrink(HotDrink drink)(drink.AddMilk();drink.Drink();ICup cupinterface=(ICup)drink;cupinterface.Wash();Note the explicit cast to ICup.This is necessary because HotDrink doesnt support the ICupinterface,but we know that the two cup objects that might be passed to

39、 this function do.However,this is dangerous because other classes deriving from HotDrink are possible,which might notsupport ICup,but could be passed to this function.To correct this,check to see if the interface issupported:static void ManipulateDrink(HotDrink drink)(drink.AddMilk();drink.Drink();i

40、f(drink is ICup)(ICup cupinterface=drink as ICup;cupinterface.Wash();The is and as operators used here are covered in Chapter 11.Chapter 9:Defining ClassesExercise 1Q.What is wrong with the following code?public sealed class MyClass(/Class members.public class myDerivedClass:MyClass(/Class members.A

41、.m yDerivedClass derives from MyClass,but MyClass is sealed and cant be derived from.Exercise 2Q.How would you define a non creatable class?A.By defining it as a static class or by defining all of its constructors as private.Exercise 3Q.Why are noncreatablc classes still useful?How do you make use o

42、f their capabilities?A.Noncreatable classes can be useful through the static members they possess.In fact,you can evenget instances of these classes through these members.Heres an example:class CreateMe(private CreateMe()(static public CreateMe GetCreateMe()(return new CreateMe();Here the public con

43、structor has access to the private constructor as it is part of the same classdefinition.Exercise 4Q.Write code in a class libraiy project called Vehicles that implements the Vehicle family ofobjects discussed earlier in this chapter,in the section on interfaces versus abstract classes.Thereare nine

44、 objects and two interfaces that reQuire implementation.A.For simplicity,the following class definitions are shown as part of a single code file rather thanlisting a separate code file for each.namespace Vehicles(public abstract class Vehicle(public abstract class Car:Vehicle(public abstract class T

45、rain:Vehicle()public interface IPassengerCarrier()public interface IHeavyLoadCarrier()public class SUV:Car,IPassengerCarrier()public class Pickup:Car,IPassengerCarrier,IHeavyLoadCarrier(public class Compact:Car,IPassengerCarrierpublic class PassengerTrain:Train,IPassengerCarrierpublic c la ss F reig

46、htT rain:T rain,IHeavyLoadCarrier(p ublic class T424DoubleBogey:T rain,IHeavyLoadCarrier()Exercise 5Q.Create a console application project,Traffic,that references V e h ic le s .d l 1(created in Exercise4).Include a function,AddPassenger(),that accepts any object with theIP a s s e n g e rC a rrie r

47、 interface.To prove that the code works,call this function using instancesof each object that supports this interface,calling the ToString()method inherited fromS ystem.O b je c t on each one and writing the result to the screen.A.using System;using V ehicles;namespace T raffic(c la ss Program(s ta

48、tic void M ain(strin g(args)(AddPassenger(new Compact();AddPassenger(new SUV();AddPassenger(new P ickup();AddPassenger(new P assengerT rain();s ta tic void A ddPassenger(IPassengerC arrier V ehicle)(C onsole.W riteLine(V ehicle.T oS tring();)Chapter 10:Defining Class MembersExercise 1Q.Write code th

49、at defines abase class,M yC lass,with the virtual method G e tS trin g ().Thismethod should return the string stored in the protected field m y S trin g,accessible through thewrite only public property C o n ta in e d S trin g.A.class MyClass(p ro tected strin g myString;p ublic strin g C ontainedSt

50、ring(se tm yString=v alu e;p u b lic v ir tu a l s tr in g G e tS trin g()re tu rn m yString;Exercise 2Q.Derive a class,M y D e riv e d C la ss,from M yC lass.Overnde the G e tS tr in g ()method toreturn the string from the base class using the base implementation of the method,but add the text”(o u

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 教育专区 > 教案示例

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知得利文库网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号-8 |  经营许可证:黑B2-20190332号 |   黑公网安备:91230400333293403D

© 2020-2023 www.deliwenku.com 得利文库. All Rights Reserved 黑龙江转换宝科技有限公司 

黑龙江省互联网违法和不良信息举报
举报电话:0468-3380021 邮箱:hgswwxb@163.com