Tải bản đầy đủ - 0 (trang)
Chapter 3.  The .NET Type System

Chapter 3.  The .NET Type System

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

Chapter3.The.NETTypeSystem

Thischapterprovidesatourthroughthe.NETtypes

neededfor.NETCompactFrameworkprogramming.

.NETprogrammingprovidesahighlevelofinteroperability

betweenprogramminglanguages.By"interoperability"we

meanthat,moresothananyotherprogramming

environment,the.NETmodelreducesdifferencesbetween

differentprogramminglanguages.Thisgivesdevelopers

greaterfreedominselectingaprogramminglanguage

(assuming,ofcourse,thata.NET-compatiblecompilerfor

adesiredlanguageisavailable).Thishighlevelof

interoperabilityhasneverbeenachievedintraditional

Windowsprogramming,andVisualBasicprogrammers

haveoftenfeltlikesecond-classcitizens.

Interoperabilityisachievedbyasetofcommonstandards.

Amongthe.NETtechnologiesthatMicrosoftsubmittedto

EcmaInternational[1]wastheCommonLanguage

Infrastructure(CLI).TheCLIcontainsbasicinfrastructure

elementsof.NETbutexcludesthehigh-levelWindows

FormsandWebFormsclasses.Tointeroperatewithother

.NET-compatiblelanguages,acompilermustcomplywith

theCLI.Thischapterfocusesononeofthosestandards:

thecommontypesystem(CTS).

[1]EcmaInternationalisaEuropeanstandardsbody;seehttp://www.ecmainternational.org.



The.NETtypesystemprovidesthefoundationfora

stronglytyped,object-orientedprogrammingenvironment.

Aprogrammerselectsthemostappropriatetypeto

representthedataitem,ineffectcodifyingthe

programmer'sintentforhowthatdataitemshouldbe

used.Oncethetypeischosen,errorscanbedetectedat



bothbuildtime(bythecompiler)andatruntime(bythe

runtimesystem).The.NETexecutionenginetakesthisone

stepfurther,supportingverifiablecode,whichrelieson

strongtypingtoensurethatthecodedoesnotaccessoutof-boundsmemory.

Anobject-orientedapproachorganizestherawmaterialof

software—meaningthecodethatrunsandthedatathatis

operatedon—asobjects.Thecontentandbehaviorofan

objectaredefined,inturn,byitstype—thatis,byits

class.Programmersuseclassestoorganizecodeanddata.

Usingtheterminologyof.NET,wesaythataclassisaset

ofmethodsandfields,whereamethodisthemost

fundamentaltypeofcode,andafieldisthemost

fundamentaltypeofdata.

Thischapterreviewstheelementsofthe.NETFramework

typesystemthat.NETCompactFrameworkprogrammers

arelikelytoneed.OurintentisnottoteachC#

programming—otherbooksarebettersuitedforthat

purpose.Norisourintenttoprovideacompletediscussion

oftheintricaciesof.NETinternals,afascinatingsubject

thatisaddressedinother,morespecialized,books.[2]

[2]WerecommendEssential.NET,Volume1:TheCommonLanguageRuntimebyDonBox

withChrisSells(Boston,MA:Addison-Wesley,2003).



BecausethisbookfocusesonC#,weexpectreadersto

havelearnedC#programmingfromothersources.

However,wedoprovideinthischaptersomespecific

sidebarsforC++programmersandVisualBasic6

programmers.

Amazon



Prev



don'tbeafraidofbuyingbooks



Next



UsingTypeInformation:Namespace

ReferencesandAssemblyReferences

Tomakeuseofatypethatisdefinedinthe.NETCompact

Framework,youreferencethelocationwherethattypeis

defined.Agiventypehasaphysicallocationandalogical

location.Thephysicallocationisafile,typicallywithan

extensionof.exeor.dll.Touseatypethatisdefinedin

a.dllfile,youletthecompilerknowthefile'slocationby

providinganassemblyreference.Withinyourcode,you

specifythelogicallocationofatypebyprovidinga

namespace.

WediscussednamespacesindetailinChapter2,soweare

notgoingtodelveintothattopicingreatdetailinthis

chapter.However,namespacesdoprovideapointof

departurefortheexplorationoftypeinformation.Aswe

discussedinChapter2,namespaceshelporganizethe

largenumberoftypesthatareinevitableinalarge,

multifacetedprogrammingenvironment.Assuch,a

namespaceprovidespartofatype'sidentity;itisthe

familynameforasetoftypes.

Forexample,theSystem.Drawingnamespaceisthefamily

oftypesusedtocreategraphicaloutput.Withinthat

namespacearetwosiblingclasses,BrushandPen.The

fullyqualifiednamesforthesetypesare

System.Drawing.BrushandSystem.Drawing.Pen.The

fullyqualifiednamegivesthesetypesauniqueidentity

amongthevastsetof.NET-compatibletypes.Ingeneral,

youprobablywillnotwanttousethefullyqualifiednames

foreveryclassyoureferto.Incaseofambiguity,however,

thefullyqualifiednameprovidesawaytodistinguish



betweensimilarlynamedclasses,structures,interfaces,

andother.NETtypes.



NamespaceContents

Anamespaceistheoutermostorganizingelementofa

type.Useofnamespacesinyourownprogramcodeis

optional,butwerecommendthatyougivesometimeand

thoughttohowyouwishtousethemwhenorganizing

codelibrariesthatotherprogrammersaregoingtouse.

Forclasslibraries,theconventionisthatthenameofa

namespaceshouldalsobethenameoftheDLLfile.For

example,inthe.NETCompactFramework,the

System.Windows.Formsnamespaceresidesinsidethe

System.Windows.Forms.dllfile.Inthesamplecodefor

thisbook,weusetheYaoDurantnamespaceforshared

librariesandforsourcefilesthatweexpectourreadersare

goingtowanttoreuse.

Withinanamespace,themostimportantkindoftypethat

youcandefineisaclass.Otherkindsoftypeinformation

canbeincludedinanamespace,suchasenumerations

andstructures.Butafterthenamespace,thesecondmost

importantorganizingelementin.NETprogrammingisthe

class.Youcannotdefinecodeordatadirectlyina

namespace—youmustputtheminaclass.

Withinaclass,codeanddataaredefinedusingthesetwo

fundamental.NETtypes:fieldsandmethods.Thefragment

inListing3.1showsafieldandamethoddefinedina

class,which,inturn,residesinanamespace,

YaoDurant.Identity.



Listing3.1.FourFundamentalTypes:aField,a

Method,aClass,andaNamespace



namespaceYaoDurant.Identity

{

publicclassSimpleType

{

publicinti;

publicintReturnInteger()

{

returni;

}

}//class

}//namespace



ThecodeinListing3.1containsexamplesoffourkey

elementsofthe.NETtypesystem:

1. Anamespace:YaoDurant.Identity

2. Aclass:SimpleType

3. Afield:i

4. Amethod:ReturnInteger

Thefullyqualifiednamefortheclassis

YaoDurant.Identity.SimpleType,andthefullyqualified

nameforthemethodis

YaoDurant.Identity.SimpleType.ReturnInteger.Inthe

nextsubsectionwediscusstheusingstatement,which

letsyoureferenceanamespacetoavoidhavingtouse

fullyqualifiednames.

Aprogramsourcefilecanhaveanynumberof

namespaces.Namespaceshelporganizethevarioustypes

thatmakeupaprogram,servingasthegeneral-purpose



containerforthosetypes.Theprimaryuseofnamespaces

thatmostprogrammersencounteriswithinframeworks,[3]

whichusenamespacestoorganizethemyriadnumberof

typesintomanageablesets.Namespacescanholdany

combinationofthefollowingtypes:

[3]Meaningthe.NETFramework,the.NETCompactFramework,andotherframeworks

thatmightbeavailable.



Classes

Interfaces

Structures

Enumerations

Delegates

Anamespacecanalsocontainothernamespaces,although

namespacesarenotconsideredatype.Fromanobjectorientedprogrammingperspective,classesarethe

preeminenttypeina.NETprogram.Aclassisableto

containallothertypes,includingotherclasses.Because

namespacesarenotatype,theycannotbecontainedin

classes.



AccessingNamespaces

Afullyqualifiednameprovidesanunambiguouswayto

identifyaclass,methodsinaclass,andstatic(orshared)

fields.Thatisagoodthing.Whenyoulookatthecode

generatedforyoubytheDesigner,youseealotoffully

qualifiednames.TheDesignerwritesthecodeforyou.It

laterreadsthecodewhenyoudecidetoeditaform.In

thiscontext,afullyqualifiednamehelpstheDesigner

avoidconfusion.



Thedisadvantageoffullyqualifiednamesisthatthey

requirealotoftyping.Toavoidthisextraeffort,C#

programmersindicatethenamespacestheywishtouse

withasetofusingstatements.Forexample,ifwehada

separatesourcefile,module,orassemblythatneededto

accessthetypesinournamespace,wewouldeliminate

theneedforfullyqualifiednameswithastatementlikethe

following:



usingYaoDurant.Identity;



AssemblyversusNamespace

ClosereadingoftheCLIrevealsthatanassembly,

notanamespace,formstheoutermostcontainerof

the.NETtypesystem.OnereasonisthatsomeCLIcompatiblelanguagesmightnotsupport

namespaces.Formostpurposes,anamespace

servesastheoutermostcontainerforeverythingin

the.NETtypesystem.Therearetimes,however,

whenanamespacefallsshortofprovidingwhatwe

need.

Aprogramsometimesneedstoidentifyitselftothe

executionengine.Thereisnonamespaceclass;

instead,weuseanobjectcreatedfromthe

Assembly[4]class.WeuseanAssemblyobjectto

accessresourcesinamodule,toloadandrun

programsandsharedlibraries,andtoqueryfor

typeinformation.

Byitself,ausingstatementhintsatdesired

namespacesbutdoesnotindicatewhatactual

moduletouse.Forthat,youmustaddareference

toaVisualStudio.NETproject,asubjectwediscuss

intheaccompanyingtext.

Onthedesktop,anassemblycanbecreatedfrom

twoormoremodules.The.NETCompact

Frameworkdoesnotsupportmultimoduleassembly,

soeveryassemblyhasexactlyonemodule

associatedwithit.



[4]Fullyqualifiedname:



System.Reflection.Assembly.



Whenyoucreateanewsmart-deviceprojectinVisual

Studio.NET,theSmartDeviceApplicationWizardcreatesa

setofusingstatementsforyou,asshowninFigure3.1.

Thesearenotneededtobuildthecodethathasbeen

generatedforyoubecausetheDesignerusesfullyqualified

names.Instead,thesereferencestelltheIDEaboutthe

namespacesneededtosupportIntelliSense.



Figure3.1.Setofusingdeclarationscreated

bytheSmartDeviceApplicationWizard

[Viewfullsizeimage]



AssemblyReferences

Anassemblyreferenceprovidesthenamesoftheshared



librariesthata.NETprogram(orsharedlibrary)isgoingto

use.Whileanamespaceisalogicalcontainerforasetof

classes(andothertypes),anassemblyisaphysical

container—thenameofoneormorelibraryfiles—that

containsclassesandother.NETtypes.Ausingstatement

providesahintofthenamespacesthatmightberequired

inanassemblybutarepurelyoptional;thisconvenient

featureeliminatestheneedforfullyqualifiednamesfor

importedtypes.

Anassemblyreference,ontheotherhand,isnotoptional.

VisualStudio.NETmustknowthenamesoftheshared

librarythataprogramisgoingtoaccessbecauseituses

thelibrarytoextractthemetadatarequiredfortype

safety.Italsoprovidesaverysecuretypeofversion

controlbyextractingthestrongnameofeachassembly,

whichtheloaderwilllaterusetoverifyacorrectmatch

beforeallowingaprogramtorun.

WhentheSmartDeviceApplicationWizardcreatesa

projectforyou,itaddsasetofassemblyreferencesto

yourproject.Figure3.2showsanexampleofthedefault

setprovidedintheSolutionExplorerwindow.Youaddnew

assemblyreferencesbysummoningtheAddReference

dialogbox.(FromtheVisualStudiomenu,selectProject

AddReference...,orright-clickontheSolutionExplorer

andselectAddReference.…)



Figure3.2.Assemblyreferencescreatedby

theSmartDeviceApplicationWizard



Theminimumassemblyreferencerequiredforall.NET

programsismscorlib.dll,ashortnamethatstandsfor

"MicrosoftCoreLibrary."Asthenameimplies,thislibrary

holdsthecoreelementsforthe.NETruntimesystem.This

soundslikeanimportantlibrarytounderstand,soyou

mightwonderhowtoexploreit.Oneapproach,whichwe

mentionedinChapter1,istouseildasm.exe—theIL

disassemblytool.AnotherapproachistousetheObject

BrowserinVisualStudio.NET.Figure3.3showstheObject

Browserdisplayingthecontentsofmscorlib.dll.(Select

theView ObjectBrowsermenuitemtosummonthe

ObjectBrowser.)Theleftsideofthefigureshowsavailable

namespacesandalsoclassesintheSystem.Threading

namespace.Therightsideshowsdetailsforthepublic

membersoftheThreadclass.



Figure3.3.TheObjectBrowsershowingthe



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

Chapter 3.  The .NET Type System

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

×