Tải bản đầy đủ - 0 (trang)
Chapter 2.  The .NET Framework: General Concepts

Chapter 2.  The .NET Framework: General Concepts

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

2.1.CommonLanguageRuntime

TheCommonLanguageRuntime(CLR)isanenvironmentthat

managescodeexecutionandprovidesapplication-development

services.Itprovidesallofthecommonfeaturesrequiredbyall

.NET-enabledlanguages.VisualBasicandother.NETlanguages

aresimplywrappersthatexposetheCLR'sfunctionality.

BecausetheCLRprovidesallofthecorefunctionalityforall

.NETlanguages,componentswrittenindifferent.NET

languagescaninteractwitheachotherimmediately,withno

language-specificconflicts.Evendatatypesaresharedamong

.NETlanguagesthroughtheCLR'sCommonTypeSystem

(CTS).WhiledatatypesmayhavedifferentnamesinVisual

BasicthantheydoinC#,theywillallbebasedonunderlying

CLRdatatypes.

TheCommonLanguageSpecification(CLS)definestheminimal

setof.NETfeaturesthatmustbeimplementedbya.NETcompliantcompiler.ComponentsdevelopedtobeCLS-compliant

maybelimitedintheirabilitytointeractwithapplicationsand

componentsthatuseawiderrangeof.NETfeatures.

Theoutputofa.NETcompilerincludesmetadata,whichis

informationthatdescribestheobjectsthatarepartofthe

generatedapplicationorlibrary.Themetadatadescribesthe

following:

Datatypesandtheirdependencies

Objectsandtheirmembers

Referencestorequiredcomponents

Information(includingversioninginformation)about



componentsandresourcesthatwereusedtobuildthe

applicationorlibrary

MetadataisusedbytheCLRtosupportfunctionalitysuchas:

Managememoryallocations

Locateandloadclassinstances

Manageobjectreferencesandperformgarbagecollection

Resolvemethodinvocations

Generatenativecode

Makesurethattheapplicationhasthecorrectversionsof

necessarycomponentsandresources

Enforcesecurity

Byincludingmetadatainacompiledsoftwarecomponent,that

componentbecomes"self-describing."ThistellstheCLR

everythingitneedstoprepareandexecutea.NETapplication,

andtoallowittointeractwithother.NETcomponents.







2.2.ManagedCode

CodecreatedwithintheCLRenvironmentiscalledmanaged

code.Applicationsandlibrariescreatedusingnon-.NETtools,

suchasVB6applications,andCOMandActiveXcomponents,

arenotmanagedcode.Youcanstilluseunmanaged

componentsinyour.NETapplications,buttheymustbe

referencedthroughspecial"interop"conduitstopreventthe

unmanagedcodefromhavinganydetrimentalimpactonthe

managedsideoftheapplication.

Havingacentralmanagerofallthings.NETliketheCLRmakes

possiblesomenicecentralizedfunctionality.Onesuchfeaturein

.NETisthegarbagecollectionsystem,whichautomatically

disposesofallvariablesanddataobjectswhenanapplicationis

finishedwiththem,reclaimingeverybyteandreleasingall

referencestotherelatedmemory.

Managedexecutionistheprocessofrunningyour.NET

applicationsinthecontextoftheCLR,althoughthisprocess

officiallystartswhenwritingyourfirstlineof.NETsourcecode.

Therearethreesimplestepstomanagedexecution.

1. Writecodeusingoneormore.NETcompilers.Some

compilers(liketheC++compilerfor.NET)cangenerate

codethatisunmanagedorthatfallsoutsidetheofficialCLS.

Suchcodecannoteasilyinteractwithcomponentsfrom

other.NETlanguages,soavoiditinmixed-language

applications.

2. Compilethecode.Thecompilertranslatessourcecodeto

IntermediateLanguagecode(IL),alsocalledMicrosoft

IntermediateLanguage(MSIL)orCommonIntermediate

Language(CIL),andgeneratesthenecessarymetadatafor

theapplication.



3. Runthecode.When.NETcodeisexecuted,theILis

compiledintoCPU-specificnativecodebyaJustInTime

(JIT)compiler.Theresultingapplicationisrunwithinthe

contextoftheCLR.

OnebenefitofrunningapplicationswithintheCLR-managed

environmentisthatdatawithintheapplicationiskeptsafe.The

CLRkeepserrantcodeandmalformeddatafrominterfering

withtherestofmemory,eitherinyourapplicationorelsewhere

inthesystem.



2.3.Namespaces

Thenotionofanamespaceplaysafundamentalroleinthe.NET

Framework.Ingeneral,anamespaceisalogicalgroupingof

types(classesandsimilarconstructs)forthepurposesof

identificationandnavigation.Therearesomanyclassesand

featuresin.NETthatthereareboundtobenameconflicts.And

sincethird-partylibrariescanbeintegratedintotheclassspace

justliketheMicrosoft-suppliedlibraries,namespaceskeep

everythingneatandorderly.

Imaginethat,inacertainbusiness,thereisanexecutive

namedJohnSmith,asecretarynamedJohnSmith,anda

custodiannamedJohnSmith.Inthiscase,thenameJohn

Smithisambiguous.Whenthepaymasterstandsonatableand

callsoutthenamesofpeopletoreceivetheirpaychecks,the

executiveJohnSmithwon'tbehappyifherushestothetable

whencustodianJohnSmith'spaycheckisinthepaymaster's

hand.

Toresolvethenamingambiguity,thebusinesscandefinethree

namespaces:Executive,Secretarial,andCustodial.Nowthe

threeindividualscanbeunambiguouslyreferredtobytheirfully

qualifiednames:

Executive.JohnSmith

Secretarial.JohnSmith

Custodial.JohnSmith

Namespacesin.NETlookalotlikethesereferencestoJohn

Smith.Theyaresimplynamesusedtogroupandorganizeallof

the.NETclassesintoahierarchy.Namespacescanbenested.



Considerthefollowingthreepossiblenamespaces.

AmericaNamespace

America.WashingtonNamespace

America.Washington.SeattleNamespace

Eachofthesenamespacescanincludeclasses(andothertypes)

andadditionalnamespaces.Andthesameclassnamecan

appearinmultiplenamespaces,eveninnestednamespaces.

America.DemographicsClass

America.Washington.DemographicsClass

America.Washington.Seattle.DemographicsClass

America.Montana.DemographicsClass

The.NETFrameworkClassLibrary(FCL)consistsofseveral

thousandclassesandothertypes(suchasinterfaces,

structures,andenumerations)thataredividedintoabout200

namespaces.Allclassesconsideredtobethe"core"languageneutralclassesof.NETappearintheSystemnamespace,orin

oneofthenestednamespaceswithinSystem.Thenamespaces

suppliedwith.NETprovidebasicsystemservices,suchas:

Basicandadvanceddatatypesandexceptionhandling(the

Systemnamespace)

Dataaccess(theSystem.Datanamespace)

User-interfaceelementsforstandardWindowsapplications



(theSystem.Windows.Formsnamespace)

User-interfaceelementsforwebapplications(the

System.Web.UInamespace)

ManyVisualBasiclanguagefeaturesareimplementedwithin

theclassesoftheMicrosoft.VisualBasicnamespace.(TheC#

andJ#languageshavecorrespondingnamespaces.)

Allclasses(andothertypes)existinanamespace,eventhe

classesofyourapplication.Bydefault,yourproject's

namespaceisatthetopofthehierarchy(nexttoSystem)and

isnamedafteryourproject'sname.Youcanalterthisbyusing

theNamespacestatementatthebeginningofacodefile,orby

definingadifferentprojectnamespacethroughtheProject

Properties.







2.4.TypesandObjects

Prettymucheverythingina.NETapplicationiscontainedina

type.Typesinclude:

Classes,whicharebasicallycollectionsofdatavalues,and

therelatedcodethatmanagesthatdata.Usuallyaclass

hasbothdataandcode,butaparticularclassmightjust

haveeitherdataorcode.InVisualBasic,aModuleisa

variationofaclass.

Interfaces,whichareclass"skeletons."Interfacesdefine

thebasicstructureofaclassbutwithouttheactual

implementation.Theyareusefulfordefiningacommon

layoutoffeaturestobesharedbymanyrelatedclasses.

Delegates,which.NETusestoimplementitsevent-driven

infrastructure.

Enumerations,whicharecollectionsofnamednumeric

elements.

Valuetypesandreferencetypes.Normally,whenyoucreate

anobject(anin-memoryinstanceofaclass),thatobject

sitsinmemorysomewhere,andyourobjectvariable

containsthememorylocationoftheobjectblock.(It'slikea

pointer,forthosefamiliarwiththeClanguageparlance.)

Thesearereferencetypes.The.NETtypesystemalso

supportsvaluetypes.Avaluetypevariablestoresthe

actualdatavalueinsteadofamemoryaddresstothetrue

locationofthedata.

Othersimilarthings.Youcansubdividethetypesystem

forever,buteverythingiseventuallycalledatype.



FromtheVisualBasicpointofview,alltypesarereallyclasses.

Ofcourse,alldataobjectsareinstancesofclasses,buteven

yoursourcecodeevenyourSubMainroutineispartofaclass,

anditmustbepartofaclasstobepartofa.NETapplication.

Classesdefineachunkofrelateddataandfunctionality.When

youdesignaclass,youaresaying,"I'mplanningoncreatingan

objectthathasthesefeaturesandthatstoresthistypeofdata

andinformation."Objectsaretheactualin-memoryinstancesof

aclass.Foramuchricherdescriptionofobjectsandother

object-orientedconcepts,seeChapter3.

TherootofthetypehierarchyistheSystem.Objectclass.All

newclassesyoudesigneventuallytiebacktothe

System.Objectclass.Thisclassprovidessomebasic

functionalityrequiredofallclassesandprovidesaconvenient

waytogenericallyidentifyanyobjectinyourapplication.







2.5.Assemblies

Anassemblyisasingle.NETexecutable(EXEfile)orlibrary

(DLLfile).Sincethesefiletypesexistedbefore.NETwas

invented,whybothertogivethemaspecialname?Well,it'snot

justthetypeoffile;it'swhatisinthefilethatcounts.(Bythe

way,a.NETpuristwillinsistthatasingleassemblycanbesplit

intomultiplefiles.Whilethisistrue,itrarelyhappens,

especiallysinceitcan'tbedonefromwithintheVisualStudio

developmentenvironment.)

Anassemblyisaunitofdeployment;thatis,it'safilethatcan

bedeployedonauser'ssystem..NETapplicationsaremadeup

ofoneormoreassemblies,allworkingtogetherforacommon

goal.Insideofanassembly,youfindthefollowing:

Theexecutablecodeofyourapplication.Generallyyouwill

haveasingleprimaryEXEassembly,plusoptionalDLL

assemblies.

Embeddeddata,suchasresources(graphics,strings,etc.).

.NET-specificsecuritypermissionsrequiredforthe

assembly.

Thetypes(classesandsoon)usedintheassembly,

includingpublicclassesthatcanbeaccessedbyother

assemblies(applications).

Listingsoftheexternaltypesandreferencesneededbythe

assembly,includingreferencestootherassemblies.These

referencesalsoindicatethespecificorminimumversion

numberexpectedforthoseexternalcomponents.



Versioninformationfortheassembly.Assembliesincludea

four-partversionnumber(major,minor,revision,andbuild,

asin"2.1.0.25"),andthisversionnumberdetermineshow

theassemblyinteractswithotherassembliesand

components..NETallowsyoutoinstalldifferentversionsof

anassemblyonasinglemachineandhavespecificversions

accessedbyotherapplications.Forinstance,youmayhave

Versions1.0and2.0ofaspellcheckingcomponentinstalled

onaworkstation,oneforanoldwordprocessor(that

requiresVersion1.0)andoneforaneweremailsystem

(thatusesVersion2.0).Bothversionscanresideonthe

samesystemwithoutconflict.Infact,bothversionscanbe

activelyrunningatthesametime,afeatureknownassideby-sideexecution.

Muchofthisinformationisstoredintheassembly'smetadata,

whichwasdiscussedearlier.Asaunit,thismetadataisknown

astheassembly'smanifest.Althoughthisissomewhat

repetitive,themanifestcontainsatleastthefollowing

information.

Thenameoftheassembly

Versioninformationfortheassembly

Securityinformationfortheassembly

Alistofallfilesthatarepartoftheassembly

Typereferenceinformationforthetypesspecifiedinthe

assembly

Alistofotherassembliesthatarereferencedbythe

assembly



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

Chapter 2.  The .NET Framework: General Concepts

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

×