Tải bản đầy đủ - 0 (trang)
Hour 11. Creating and Calling Methods

Hour 11. Creating and Calling Methods

Tải bản đầy đủ - 0trang

Hour11.CreatingandCallingMethods

You've now spent about 11 hours building the basic skills

necessarytonavigateC#andtocreateanapplicationinterface.

Creating a good interface is extremely important, but it's only

one step toward creating a Windows program. After you've

createdthebasicinterfaceofanapplication,youneedtoenable

the program to do something. The program may perform an

actionallonitsown,oritmayperformactionsbasedonauser

interacting with the interface—either way, to make your

application perform tasks, you write C# code. In this hour,

you'lllearnhowtocreatesetsofcode(calledclasses),andhow

tocreateandcallisolatedcoderoutines(calledmethods).

Thehighlightsofthishourincludethefollowing:

Creatingstaticclassmembers

Creatingmethods

Callingmethods

Exitingmethods

Passingparameters

Avoidingrecursivemethods

Workingwithtasks







Top











CreatingClassMembers

Aclassisaplaceto storethecodeyouwrite.Before

youcanbeginwritingC#code,youmuststartwitha

class.Asmentionedinprevioushours,aclassisused

as a template to create an object (which may have

propertiesand/ormethods).Propertiesandmethodsof

classes can be either instance members or static

members. Instance members are associated with an

instance of a class—an object created from a class

using the keyword new. On the other hand, static

members belong to the class as a whole, not to a

specific instance of a class. You've already worked

with one class using instance members to create a

form (refer to Hour 5, "Building Forms—Part I, for

moreinformation).Whenyoudouble-clickanobjecton

a form, you access events that reside in the form's

classmodule.

Other languages, such as Visual Basic, differentiate between

class methods and public methods that are globally available

outside of a class. C# requires all methods to exist in the

context of a class, but a globally available method can be

achieved by defining static methods in your class. Static

methodsarealwaysavailableregardlessofwhetheraninstance

of the class exists. In fact, you can't access a static member

throughaninstanceofaclass,andattemptingtodosoresults

inanexception(error).



Classes are used as templates for the instantiation of

objects. I discuss the specifics of creating objects in

Hour17,"DesigningObjectsUsingClasses."Mostof

the techniques discussed in this hour apply to class

moduleswithinstancemembers(methodsthatarepart

of an instantiated object), but I'm going to focus this

discussion on static members because they are easier

touse(youcancreateandusestaticmethodswithout

gettingintothecomplicationsofcreatingobjects).

Although you could place all your program's code into a single

class module, it's best to create different modules to group

different sets of code. In addition, it's best not to place code

that isn't specifically related to a form within a form's class

module;placesuchcodeinthelogicalclassorinaspecialized

classmodule.



The current development trend centers on objectoriented programming, which revolves around class

modules. I'll give you a primer on object-oriented

programminginHour17, but this is a very advanced

topic so I won't be covering it in detail. I highly

recommend that you read a dedicated object-oriented

book, such as Sams Teach Yourself Object-Oriented

Programming in 21 Days, after you are comfortable

withthematerialinthisbook.

One general rule for using static members is that you should

create classes to group related sets of code. This isn't to say

you should create dozens of classes. Rather, group related

methods into a reasonably sized set of classes. For instance,

you might want to create one class that contains all your



printing routines and another that holds your data-access

routines.Inaddition,Iliketocreateageneral-purposeclassin

whichtoplaceallthevariousroutinesthatdon'tnecessarilyfit

intoamorespecializedclass.

Start C# now and create a new Windows Application project

namedStaticMethods.

Change the name of the default form to fclsExample, set its

Text property to Method Example, and set the Main() entry

pointoftheprojecttoreferencefclsExampleinsteadofForm1.

ChangetheSizepropertyoftheformto371,300.Next,adda

newclasstotheprojectbychoosingAddClassfromtheProject

menu.C#thendisplaystheAddNewItemdialogbox,asshown

inFigure11.1.

Figure11.1.Allnewprojectitemsareaddedusingthis

dialogbox.



Note that this is the same dialog box used to add new forms.



ChangethenameoftheclasstoclsStaticExample.csandclick

Open. C# then creates the new class and positions you in the

codewindow—readytoentercode(seeFigure11.2).

Figure11.2.Classeshavenographicalinterface,soyou

alwaysworkwiththeminthecodeeditor.



SaveyourprojectnowbyclickingSaveAllonthetoolbar.







Top











WritingMethods

After you've created the class(es) in which to store

yourcode,youcanbeginwritingmethods.Amethodis

a discrete set of code that can be executed. Methods

are much like events, but rather than being executed

byauserinteractingwithaformorcontrol,methods

areexecutedwhencalledbyacodestatement.

The first thing to keep in mind is that every method should

perform a specific function, and it should do it very well. You

shouldavoidcreatingmethodsthatperformmanytasks.Asan

example of the use of methods, consider that you want to

create a set of code that, when called, draws an ellipse on a

form.Youalsowantasecondmethodtocleartheform.Ifyou

placed both sets of code into the same method, the ellipse

would be drawn and then would immediately be erased. By

placing each set of code in its own method, you can draw the

ellipse by calling one method and then erase it at any time by

calling the other method. By placing these routines in a class

rather than attaching them to a specific form, you also make

themethodsavailabletoanyformthatmayneedthem.

TherearetwotypesofmethodsinC#:

Methodsthatreturnavalue

Methodsthatdonotreturnavalue(void)

There are many reasons to create a method that returns a

value. For example, a method can return true or false,



depending on whether it was successful in completing its task.

You could also write a method that accepts certain parameters

(datapassedtothemethod,incontrasttodatareturnedbythe

method) and returns a value based on those parameters. For

example, you could write a method that lets you pass it a

sentence,andinreturnitpassesbackthenumberofcharacters

in the sentence. The possibilities are limited only by your

imagination. Just keep in mind that a method doesn't have to

returnavalue.



DeclaringMethodsThatDon'tReturnValues

Becauseyou've already created a class, you're ready to create

methods (to create a method, you first declare it within a

class).

Position the cursor to the right of the closed brace (}) that

signifiestheendofthepublicclsStaticExampleblockandpress

Enter to create a new line. Enter the following three

statements:



publicstaticvoidDrawEllipse(System.Windows.Forms.For

{

}

Next,positionyourcursortotherightoftheopenbrace({)and

pressEntertocreateanewlinebetweenthetwobraces.Thisis

whereyou'llplacethecodeforthemethod.

The declaration of a method (the statement used to define a

method) has a number of parts. The first word, public, is a

keyword (a word with a special meaning in C#). The keyword

public defines the scope of this method, designating that the

method can be called from code contained in modules other

thantheonecontainingthedefinedmethod(scopeisdiscussed



indetailinthenexthour).Youcanusethekeywordprivatein

placeofpublictorestrictaccessofthemethodtocodeonlyin

themoduleinwhichthemethodresides.

The word static is another C# keyword. As mentioned earlier,

static members belong to a class as a whole, not to a specific

instance of a class. This will allow the DrawEllipse() method to

beaccessedfromotherclasseswithouthavingtoinstantiatean

clsStaticExampleobject.

ThewordvoidisanotherC#keyword.Thevoidkeywordisused

to declare a method that doesn't return a value. Later in this

hour, you will learn how to create methods that do return

values.

Thethirdword,DrawEllipse, is the actual name of the method

andcanbeanystringoftextyouwantittobe.Note,however,

thatyoucan'tassignanamethatisakeyword,norcanyouuse

spaceswithinaname.Inthisexample,themethodisgoingto

drawanellipseontheform,soyouusedthenameDrawEllipse.

You should always give method names that reflect their

purpose.Youcanhavetwomethodswiththesamenameonlyif

theyhavedifferentscope(discussedinthenexthour).



Some programmers prefer the readability of spaces in

names,butinmanyinstances,suchaswhennaminga

method, spaces can't be used. A common technique is

touseanunderscore(_)inplaceofaspace,suchasin

Draw_Ellipse. This isn't a recommended practice,

however.

Immediatelyfollowingthenameofthemethodisaset

of parentheses surrounding some text. Within these

parentheses you can define parameters—data to be



passed to the method by the calling program. In this

example, you've created a parameter that accepts a

reference to a form. The routine will draw an ellipse

onwhateverformispassedtotheparameter.

Parentheses must always be supplied, even when a

procedure doesn't accept any parameters (in which

casenothingisplacedbetweentheparentheses).

AddthefollowingcodetoyourDrawEllipsemethod:



System.Drawing.GraphicsobjGraphics;

System.Drawing.RectanglerecDrawRectangle;

recDrawRectangle=frm.DisplayRectangle;

recDrawRectangle.Inflate(-5,-5);

objGraphics=frm.CreateGraphics();

objGraphics.Clear(System.Drawing.SystemColors.Control);

objGraphics.DrawEllipse(System.Drawing.Pens.Blue,recDr

objGraphics.Dispose();

MuchofthiscodeissimilartoacodeexamplediscussedinHour

3,"UnderstandingObjectsandCollections,"soI'mnotgoingto

go over it in detail. Basically, this routine creates a rectangle

withthesamedimensionsastheclientrectangleofthesupplied

form.Then,theInflatemethodisusedtoreducethesizeofthe

rectangle by 5 pixels in each dimension. Finally, a graphics

object is created and set to reference the client area of the

supplied form, and a rectangle is drawn within the boundaries

oftherectangle.

Whenyou'vefinishedenteringyourcode,itshouldlooklikethat

inFigure11.3.



Figure11.3.Allcodeforamethodmustresidebetween

theopenandclosebracesofthemethod.



Now you're going to create a procedure that erases the ellipse

from a form. Place the caret (cursor) at the end of the closing

brace (} ) for the DrawEllipse() method and press enter to

createanewline.Enterthefollowingthreestatements:



publicstaticvoidClearEllipse(System.Windows.Forms.Fo

{

}

AddthefollowinglineofcodetotheClearEllipse()methodona

newlinebetweentheopeningandclosingbraces:



frm.Refresh();

This single line of code forces the designated form to refresh

itself.Becausetheellipsethatwasdrawnbythefirstprocedure

isn'tpartoftheform(itwassimplydrawnontotheform),the



ellipseiscleared.



DeclaringMethodsThatReturnValues

The two methods you've created so far don't return

values. You're now going to declare a method that

returns a value. Here's the general syntax for the

methodyouwillcreate:

[modifiers]datatypeMethodName(parameters)

You'll notice one key difference between declaring a method

that doesn't return a value and declaring one that does: you

have to define the data type of the value returned. Previously,

you used the keyword void to declare that no value was being

returned.Datatypesarediscussedindetailinthenexthour,so

it's not important that you fully understand them now. It is

important,however,thatyouunderstandwhatishappening.

The data type entered before the method name denotes the

type of data returned by the method. The method that you're

about to enter returns a numeric value of type integer. If the

methodweretoreturnastringoftext,itwouldbedeclaredas

string. It is very important that you declare the proper data

typeforyourfunctions.

Position the cursor to the right of the closing brace for the

ClearEllipse() method, press Enter to create a new line, and

enterthefollowingthreestatements:



publicstaticintComputeLength(stringstrText)

{

}



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Hour 11. Creating and Calling Methods

Tải bản đầy đủ ngay(0 tr)

×