Tải bản đầy đủ - 0 (trang)
1 Understanding Visual C# .NET Program Layout

1 Understanding Visual C# .NET Program Layout

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

Listing1.1ASimpleVisualC#.NETConsole

Application



usingSystem;



namespace_1_ProgramLayout

{

///

///SummarydescriptionforClass1.

///


classDateTimePrinter

{

///

///Themainentrypointfortheapplication.

///


[STAThread]

staticvoidMain(string[]args)

{

Console.WriteLine("Todayis{0}",DateTime.Now);



}

}

}

Thefirstcoupleoflinesrelatetoanorganizationalconstruct

knownasthenamespace.Namespacesconveyasenseof

relationshipsbetweenlikeobjects.Forinstance,ifyouhave

someobjectswithsuchnamesasFrame,Engine,Wheel,Light,

andSeat,youimmediatelyseetherelationshiptheseobjects

possessinthattheyallbelongonanautomobile.Inthis

example,thenamespacecouldbeAutomobile.

Onthefirstline,theprogramislettingthecompilerknowthatit

wantstousesomeoftheobjectswithintheSystemnamespace.

Therefore,anytimeyouwanttouseoneoftheseobjects,you

donotneedtoprefacetheobjectnamewiththenamespace

name.Forinstance,theWriteLinestatementprintsoutasmall

messageintheconsole.TheConsoleobjectisaclasswithin

theSystemnamespace.Withouttheusingdirective,youhave

toqualifyeachtypeyouwanttousewiththenamespaceitis

declaredin.Inthisinstance,thelineinListing1.1wouldbe



System.Console.WriteLine("Todayis{0}",DateTime.Now);

Inthelisting,youcanseeanamespacedeclaration,whichis

simplythenameyougavetheprojectwhenyouinitiallycreated

it.Althoughthewizardplacedaninitialtypeinanamespacefor

youtouse,thenamespacedeclarationitselfispurelyoptional.

However,werecommendthatyoudogetintothehabitofusing



namespacestoenhancecodeorganizationandreadability.

Withintheautomaticallygeneratednamespaceisaclasscalled

Class1,whichwasrenamedtoDateTimePrintertomore

accuratelydescribethetype'sfunctionality(albeitsomewhat

limited).Aclassisbestdescribedasadatatypethatcan

containvariousassociatedmethodstointeractwithit.

Wheneveraninstanceofthatclassiscreatedorinstantiated,it

becomesausableobjecttowhichyoucangetorsetvarious

properties,receivenotificationofcertainevents,andtellitto

performsomeactionusingoneofitsmemberfunctions.

Chapter2,"ObjectsandComponents,"delvesdeeperintothe

manywaysclassesareusedwithinC#andthe.NET

Framework.

Thelastimportantcomponentofoursimpleconsoleapplication

istheapplication'sentrypoint,denotedbythestaticmember

functionMain.Eachapplicationmustcontainanentrypointso

thattheCommonLanguageRuntime(CLR)caneffectivelystart

theapplicationbyhandingcontrolovertoyou.OncetheMain

functionexits,theapplicationends.JustbeforetheMain

methoddeclarationistheSTAThreadattribute.Thisattribute

denotesthethreadingmodelyourapplicationuses.However,it

isonlyapplicableifyouplantouseCOMInterop,discussedin

Chapter24,"COMInterop,"andisignoredifyoudonot.



1.2ParsingCommand-LineArguments

Youwantyourapplicationtosupportcommand-lineargumentparsing.



Technique

Useastringarrayasaparameterinyourapplication'sentry

point,thestaticMainfunction.



usingSystem;



namespace_2_CommandLineArgs

{

classClass1

{

staticvoidMain(string[]args)

{



foreach(stringarginargs)

Console.WriteLine(arg+"\n");

}

}

}



Comments

TheMainfunctioninanapplicationhastheoptionofaccepting

astringarrayasaparameter.Thisarraycontainsthe

command-lineargumentspassedtoitbythesystemwhere

eachelementinthearraycorrespondstoastringonthe

commandlinedelineatedbyquotationmarksorwhitespace.



1.3CreatingMultipleApplicationEntryPoints

Youwantyourapplicationtocontainseveralentrypoints.



Technique

Foreachentrypointyouwanttoadd,createaseparateclass

containingastaticMainmemberfunction.Tochangewhich

entrypointisrunbytheCLR,gototheprojectproperties

(Alt+P,P)andselectCommonProperties,General.Selectthe

functionyouwanttouseastheapplicationentrypointinthe

StartupObjectfield.Youmustthenrecompileyourprojectany

timeyouchangetheapplicationentrypointbecauseyoucan

onlychangetheentrypointatcompiletime,notatruntime.



Comments

Thereareseveralreasonswhycreatingseveralapplication

entrypointsisadvantageous.Onekeyadvantageisthatit

allowsyoutocontroltheflowofyourapplicationtotest

differentavenuesoffunctionality.Forinstance,youcancreate

anentrypointthatservestodisplayatremendousamountof

debugginginformationatruntime.Whenyouareconfidentthat

theunittestsyoucreatedareworkingcorrectly,youcancreate

afinalapplicationentrypointthatremovesmostofthe

debugginginformation.However,inthepast,youmighthave

hadtocommentoutorremovethecriticaldebugging

information.Bycreatingaseparateentrypoint,yougainthe



advantageofpreservingyourunitteststhatyoucanrunsimply

bychangingapropertywithinyourproject.Withalittleclever

command-linecompiling,youcanevencreateanautomated

testharnessthatcompilesyourapplication,specifyingoneof

yourunit-testapplicationentrypoints;verifythattheresults

aresatisfied;andrepeatthatprocessforeachentrypoint.

TocompileaC#programfromthecommandlineandspecify

whichstartupobjecttouseastheapplicationentrypoint,use

the/maincommand-lineargumentforthecompiler.Listing1.2

containsaprojectsourcefilethatcontainsthreedifferent

applicationentrypoints.Tocompilethisfileonthecommand

lineandspecifyanapplicationentrypoint,youinvoketheC#

compilerusingthefollowing:



csc.exeClass1.cs/main:_3_MultEntryPoints.EntryPointTest.Main3



Listing1.2AC#ApplicationContainingMultiple

ApplicationEntryPoints



usingSystem;



namespace_3_MultEntryPoints

{

classEntryPointTest



{

classMain1Entry

{

[STAThread]

staticvoidMain(string[]args)

{

Console.WriteLine("RunninginMain");

}

}

classMain2Entry

{

[STAThread]

staticvoidMain(string[]args)

{

Console.WriteLine("RunninginMain2");

}

}

classMain3Entry



{

[STAThread]

staticvoidMain(string[]args)

{

Console.WriteLine("RunninginMain3");

}

}

}

}



1.4ReferencingAssembliesandNamespaces

Youwanttouseaclass,butthecompilersaysthattheclasscannotbe

found.



Technique

Addareferencetotheassemblythatdefinestheclassby

clickingontheProject,AddReferencefromthemainmenu.

Selectthe.NETtab,locatetheassemblythatcontainsthetype

youwanttouse,anddouble-clickit.



Comments

The.NETFrameworkusesinformationinanassemblytoresolve

typeinformationwhenyouwanttouseaclass.Anassemblyis

simplythefilethatiscreatedwhenyoucompileaprojectsuch

asan.exeordynamiclinklibrary(.dll)file.Whenyou

performthestepsofreferencinganassembly,thecompiler

knowstolookineachreferencedassemblyduringcompilation

toresolveanytypesthatareencounteredwithinthesourcefile.



1.5CreatingValidIdentifierNames

Youwanttoensurethattheidentifierfollowstherulesofvalididentifier

naming.



Technique

YouridentifiercannotbethesameasthatofaC#keyword.You

arefreetouseanycombinationofletters,numbers,and

underscorecharactersaslongastheidentifierdoesnotstart

withanumber.Furthermore,youcanusethe@symbolasthe

firstcharacterinyouridentifier.Listing1.3showsseveralvalid

andinvalididentifiernames.



Listing1.3DemonstratingValidandInvalid

IdentifierNames



namespace_5_Identifiers

{

classClass1

{

[STAThread]

staticvoidMain(string[]args)



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

1 Understanding Visual C# .NET Program Layout

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

×