Tải bản đầy đủ (.pdf) (1,244 trang)

2003 sybex c sharp complete

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (7.66 MB, 1,244 trang )

C#Complete
bySybexInc.
Sybex©2003(974pages)

ISBN:0782142036

Aclearpictureofeverythingyouneedtoknowfordeveloping
applicationsusingC#.
CompanionWebSite


BackCover
C#Complete
Introduction
HowThisBookIsOrganized
AFewTypographicConventions
ForMoreInformation
AbouttheContributors
Chapter1:IntroductiontoVisualC#andthe.NETFram
DevelopingYourFirstC#Program
IntroducingVisualStudio.NET
Usingthe.NETDocumentation
Summary
What'sNext
Chapter2:ZenandNow¡ªTheC#Language
Identifiers
Keywords
Variables
Types
TypeConversion
CommentingCode


Operators
FlowControlStatements
Structs
Exceptions
Summary
What'sNext
Chapter3:Strings,Dates,Times,andTimeSpans
UsingStrings
CreatingDynamicStrings
RepresentingDatesandTimes
UsingTimeSpans
Summary


What'sNext
Chapter4:Object-OrientedProgramming
IntroducingClassesandObjects
DeclaringaClass
CreatingObjects
UsingMethods
DefiningProperties
WorkingwithEvents
UsingAccessModifiers
CreatingandDestroyingObjects
IntroducingStructs
Summary
What'sNext
Chapter5:DerivedClasses
IntroducingInheritance
LearningaboutPolymorphism

SpecifyingMemberAccessibility
HidingMembers
Versioning
UsingtheSystem.ObjectClass
UsingAbstractClassesandMethods
DeclaringSealedClassesandMethods
CastingObjects
OperatorOverloading
Summary
What'sNext
Chapter6:Arrays,Indexers,andCollections
Arrays
Indexers
CollectionClasses
Summary
What'sNext
Chapter7:ReflectingonClasses


AssembliesandNamespaces
.NETNamespaces
Reflection
TrackingMemberswiththeClassViewWindow
NavigatingwiththeObjectBrowser
CreatingaClassLibrary
What'sNext
Chapter8:BuildingaBetterWindowsInterface
RoundButtonsDancing
ListBoxesListing
Menus

DoingtheCommonDialogThing
MDIApplications
What'sNext
Chapter9:BuildingDesktopApplications
DesktopApplicationTypes
WritingConsoleApplications
ResourceEssentials
WritingWindowsApplications
ApplicationDebugging
Summary
What'sNext
Chapter10:WorkingwithThreads
AnOverviewofThreads
WorkingwithThreads
UnderstandingCriticalSections
UnderstandingThreadSafety
UsingYourKnowledge
What'sNext
Chapter11:OverviewoftheADO.NETClasses
TheManagedProviderandGenericDataSetClasses
PerformingaSQLSELECTStatementandStoringtheR
Summary


What'sNext
Chapter12:ADO.NETApplicationDevelopment
ComparingADOtoADO.NET
UsingOleDbDataAdapterforDataTransfertoADO.NET
WritingaDataReaderApplication
WritingaDatasetApplication

ImportingandExportingXMLExample
UsingStringBuildertoImprovePerformance
Summary
What'sNext
Chapter13:UsingDataSetObjectstoStoreData
TheSqlDataAdapterClass
TheDataSetClass
WritingandReadingXMLUsingaDataSetObject
MappingTablesandColumns
ReadingaColumnValueUsingStronglyTypedDataSet
CreatingaDataAdapterObjectUsingVisualStudio.
CreatingaDataSetObjectUsingVisualStudio.NET
Summary
What'sNext
Chapter14:UsingDataSetObjectstoModifyData
TheDataRowClass
TheDataColumnClass
AddingRestrictionstoDataTableandDataColumnObj
Finding,Filtering,andSortingRowsinaDataTable
ModifyingRowsinaDataTable
RetrievingNewIdentityColumnValues
UsingStoredProcedurestoAdd,Modify,andRemove
AutomaticallyGeneratingSQLStatements
ExploringtheDataAdapterandDataTableEvents
DealingwithUpdateFailures
UsingTransactionswithaDataSet
ModifyingDataUsingaStronglyTypedDataSet


Summary

What'sNext
Chapter15:IntroductiontoC#WebApplications
Theweb.configandmachine.configFiles
SiteHierarchyversusDirectoryHierarchy
InsideConfigurationFiles
CreatingCustomConfigurationSections
ConfigurationFileLocationandLockSettings
What'sNext
Chapter16:UsingXMLinWebApplications
IntroductiontotheSystem.XmlNamespace
ReadingXMLDocuments
UsingtheXmlDataDocumentClass
TheXmlExceptionClasses
PerformingXSLTTransformsProgrammatically
What'sNext
Chapter17:WebServices
BuildingaWebService
ConsumingaWebService
SOAP(SimpleObjectAccessProtocol)
FindingWebServices(UDDI)
What'sNext
Chapter18:BuildingYourOwnWebControls
BuildingaUserControl
BuildingaCompositeControl
BuildingaCustomServerControl
TransferringDataBetweenASP.NETWebFormsandCom
What'sNext
Chapter19:OvercomingHolesinthe.NETFramework
WhyAccesstheWin32API?
Win32AccessforC#Developers

Win32AccessforVisualBasicDevelopers
Summary


What'sNext
Chapter20:OvercomingSecurityIssues
AnOverviewofWindowsSecurity
UsingtheAccessControlEditor
UsingtheSecurityConfigurationEditor
UnderstandingHow.NETRole-BasedSecurityDiffers
LookingUpanAccountSIDExample
UsingtheGetFileSecurity()FunctionExample
WorkingwithanACEsExample
Summary
What'sNext
Chapter21:GettingStartedwiththeMobileInternetT
IntroducingtheMicrosoftMobileInternetToolkit
TheOpenwaveSDK
SupportedDevices
GettingStarted
BuildingaSimpleTwo-CardDeck
UsingCodeBehind
Summary
BonusChapter:WorkingwithWin32APIData
AShortViewofData
WorkingwithVariables
WorkingwithDataStructures
WorkingwithPointers
WorkingwithEnumerations
ImportingResources

Summary


BackCover
C#Completeisaone-of-a-kindbook--valuablebothforitsbroadcontentandits
lowprice.Whetheryou'rebrand-newtoC#programming,aremigratingfrom
VisualBasicorVisualC++toC#,orhavealreadydevelopedsomeexpertisein
C#,you'llgettheskillsyouneedtobecomeproficientwithMicrosoft's
powerfulnewlanguagedesignedforthe.NETplatform.Creatingcomplex
applicationsinthe.NETFrameworkismadeeasierwithC#--Microsoft'sfirst
trueobject-orientedprogramminglanguage.
InC#Complete,you'llgetaclearpictureofeverythingyouneedtoknowfor
developingapplicationsusingC#.You'llbeginbylearningtheessential
elementsofthelanguageandofVisualStudio.NET,inwhichyou'lldevelop
andrunprogramsinacomprehensiveintegrateddevelopmentenvironment.
You'llseehowtocreatefunctionalandexcitinguserinterfacesanddesktop
applicationswrittenwithC#,andhowtoincorporatethreadstotheirbest
advantage.You'llexploretheuseofADO.NETclassesindevelopmentofC#
databaseapplications.ChaptersonASP.NETWebServiceswillwalkyou
throughthebuildingofanXMLwebservicesapplication.You'llalsovisitsome
advancedtopics,includingdesigningwithsecurityinmind,overcomingthe
shortcomingsofthe.NETFramework,andworkingwiththeMicrosoftMobile
InternetToolkit.
C#CompleteintroducesyoutotheworkofsomeofSybex'sfinestauthors,so
you'llknowwheretogotolearnevenmoreaboutC#andthe.NETFramework.


C#Complete
AssociatePublisher:JoelFugazzotto
AcquisitionsEditor:DeniseSantoroLincoln

DevelopmentalEditor:CarolHenry
CompilationEditor:MattTagliaferri
ProductionEditor:KellyWinquist
Copyeditor:RebeccaRider
Compositor:RoziHarris,InteractiveCompositionCorporation
Proofreaders:NancyRiddiough,YarivRabinovitch,EmilyHsuan,
LeslieHigbeeLight,LaurieO'Connell,MoniqueVandenberg
Indexer:NancyGuenther
BookDesigner:MaureenForys,HappenstanceType-O-Rama
CoverDesigner:DesignSite
CoverIllustrator:SuzaScalora,PhotoDisc
Copyright©2003SYBEXInc.,1151MarinaVillageParkway,
Alameda,CA94501.Worldrightsreserved.Nopartofthispublication
maybestoredinaretrievalsystem,transmitted,orreproducedinany
way,includingbutnotlimitedtophotocopy,photograph,magnetic,or
otherrecord,withouttheprioragreementandwrittenpermissionof
thepublisher.
LibraryofCongressCardNumber:2002115481
ISBN:0-7821-4203-6
SYBEXandtheSYBEXlogoareeitherregisteredtrademarksor
trademarksofSYBEXInc.intheUnitedStatesand/orothercountries.
ScreenreproductionsproducedwithFullShot99.FullShot99©1991–
1999InbitIncorporated.Allrightsreserved.FullShotisatrademarkof
InbitIncorporated.
ScreenreproductionsproducedwithCollageComplete.
CollageCompleteisatrademarkofInnerMediaInc.
NetscapeCommunications,theNetscapeCommunicationslogo,
Netscape,andNetscapeNavigatoraretrademarksofNetscape



CommunicationsCorporation.
NetscapeCommunicationsCorporationhasnotauthorized,
sponsored,endorsed,orapprovedthispublicationandisnot
responsibleforitscontent.NetscapeandtheNetscape
CommunicationsCorporateLogosaretrademarksandtradenamesof
NetscapeCommunicationsCorporation.Allotherproductnames
and/orlogosaretrademarksoftheirrespectiveowners.
Internetscreenshot(s)usingMicrosoftInternetExplorerreprintedby
permissionfromMicrosoftCorporation.
TRADEMARKS:
SYBEXhasattemptedthroughoutthisbooktodistinguishproprietary
trademarksfromdescriptivetermsbyfollowingthecapitalizationstyle
usedbythemanufacturer.
Theauthorandpublisherhavemadetheirbesteffortstopreparethis
book,andthecontentisbaseduponfinalreleasesoftwarewhenever
possible.Portionsofthemanuscriptmaybebaseduponpre-release
versionssuppliedbysoftwaremanufacturer(s).Theauthorandthe
publishermakenorepresentationorwarrantiesofanykindwith
regardtothecompletenessoraccuracyofthecontentshereinand
acceptnoliabilityofanykindincludingbutnotlimitedtoperformance,
merchantability,fitnessforanyparticularpurpose,oranylossesor
damagesofanykindcausedorallegedtobecauseddirectlyor
indirectlyfromthisbook.
ManufacturedintheUnitedStatesofAmerica
10987654321


Introduction
C#Completeisaone-of-a-kindcomputerbook—valuablebothforthe
breadthofitscontentandforitslowprice.Thisthousand-page

compilationofinformationfromsomeofSybex'sverybestbooks
providescomprehensivecoverageoftheC#programminglanguage.
Thisbook,uniqueinthecomputerbookworld,wascreatedwith
severalgoalsinmind:
Toofferathoroughguidecoveringalltheimportantuser-level
featuresofC#atanaffordableprice
Toacquaintyouwithsomeofourbestauthors,theirwriting
stylesandteachingskills,andthelevelofexpertisetheybring
totheirbooks—sothatyoucaneasilyfindamatchforyour
interestsandneedsasyoudelvedeeperintoC#.
ThusC#Completeisdesignedtoprovideyouwithalltheessential
informationyou'llneedtogetthemostfromtheC#languageandthe
.NETFramework.Atthesametime,C#Completewillinviteyouto
exploretheevengreaterdepthandwidercoverageofmaterialinthe
originalbooks.
Ifyouhavereadothersoftwaredevelopmentbooks,youhaveseen
thatthereareasmanydifferentprogrammingstylesasthereare
programmers.ThebooksfromwhichC#Completewascompiled
representthisrangeofdevelopmentstyles.Fromtheessential,
fundamentalexamplesfoundinVisualC#Programmingtothemore
advancedanddetailedwork.NETFrameworkSolutions:InSearchof
theLostWin32API,youwillbeabletochooseanapproachanda
levelofexpertisethatworksbestforyou.Youwillalsoseewhatthese
bookshaveincommon:acommitmenttoclarity,accuracy,and
practicality.
Inthesepages,youwillfindampleevidenceofthehighqualityof
Sybex'sauthors.Unlikepublisherswhoproduce"booksby
committee,"Sybexauthorsareencouragedtowriteintheirindividual
voices,voiceswhichreflecttheirownexperiencewiththesoftwareat



handandwiththeevolutionoftoday'spersonalcomputers,soyou
knowyouaregettingthebenefitoftheirdirectexperience.Nearly
everybookrepresentedhereistheworkofasinglewriterorapairof
closecollaborators.Similarly,allofthechaptersherearebasedon
theindividualexperienceoftheauthors,theirfirst-handtestingofprereleasesoftware,andtheirsubsequentexpertisewiththefinal
product.
InadaptingthevarioussourcematerialsforinclusioninC#Complete,
thecompilationeditorpreservedtheseindividualvoicesand
perspectives.Chapterswereeditedtominimizeduplication,omit
coverageofnonessentialinformation,updatetechnologicalissues,
andrevisethecross-referencingsoyoucaneasilyfollowatopic
acrosschapters.Somesectionsmayhavebeeneditedforlengthin
ordertoincludeasmuchupdated,relevant,andimportantinformation
aspossible.


WhoCanBenefitfromThisBook?
C#Completeisdesignedtomeettheneedsofawiderangeof
programmersanddevelopersworkingwiththeC#language.C#has
someelementsthateveryoneuses,aswellasfeaturesthatmaybe
essentialonlytosome.Therefore,althoughyoucouldreadthisbook
frombeginningtoend,notallofyouwillneedtoreadeverychapter.
Thecontentsandtheindexwillguideyoutothesubjectsyou're
lookingfor.You'llfindeverythingfromtheessentialsofC#tothe
elementsofadvancedC#development,aswellasimportanthelpwith
C#-basedapplicationanddatabasedevelopment,andexcellent
coverageofusingC#todevelopwebapplicationsandwebservices.
BeginnersEvenifyouhaveonlyalittlefamiliaritywith
programming,thisbookwillstartyouworkingwiththeC#

languageandthe.NETFramework.You'llfindstep-by-step
instructionsforthecreationofyourfirst"HelloWorld"program,
andwillslowlybuilduptomorecomplexandusefulsoftware.
You'llwanttostartattheverybeginningofthisbookandreadthe
firstsevenchaptersthatcoverthebasics.
IntermediateLevelIfyouhavesomebackgroundinsoftware
development,perhapsevensomeexperienceinC#orVisual
Basic,you'llfindmostofthisbookcontainsusefulnuggetsof
informationthroughout.The.NETFrameworkisavastsetof
librariesandhasbeenavailableforonlyarelativelyshorttime,so
itisoftenusefultoseewhatotherdevelopershaveuncovered
duringtheirmasteringofthisnewlanguage.
Advanced"Bitheads"Theadvanceddeveloperwillfindthis
bookusefulinlearningallthedifferencesbetweenthe.NET
languagesandthe"oldways."Forexample,ADO.NET
representsanentirelynewwaytoconnecttoaback-end
database,andwiththisnewfunctionalitycomenewtricksand
caveats.Thisisjustoneofthehundredsofchangessincewe
enteredtheC#worldfrompreviouslanguagessuchasC++.


Garbagecollection,threaduse,andXMLWebServicesrepresent
othernewchallengestotheexperienceddeveloper.


HowThisBookIsOrganized
Here'salookatwhatC#Completecovers:
ThefirstsevenchaptersofC#CompleteintroduceyoutoVisualC#
.NETessentials.ThisincludestheC#language,the.NETFramework,
andVisualStudio.NET—thetoolthatMicrosoftprovidesforthe

creationofyourprograms.You'lllearnhowtocreateapplicationsof
varioustypes,andyou'llbegintodiveintotheenormoussetoftools
andclassesfoundwithinthe.NETFramework.You'llalsobeginto
learnthebasicC#syntax.
StartingwithChapter8,weputthepiecestogetherandshowhow
completeapplicationsaredeveloped.Chapters8and9explorethe
varioustypesofapplications,includingconsoleapplicationsvs.
"standard"Windowsapplications.You'llseeexamplesofwhereeach
typecanbeuseful.Chapter10givesyouimportantmaterialaboutthe
advantagesandpitfallsofthreads.
Mostapplicationsexisttoreadandwritesomesortofdata,so
connectivitytodatabasesisobviouslyofgreatimportance.The
processofdatabasedevelopmentchangesprettydramaticallyin.NET
languages,andChapters11through14willintroduceyoutoallthe
newwaystopumpdatainandoutofdatabaseslikeSQLServer.
Nextcomethefourimportantchapters(15through18)onASP.NET
andwebservices.Webapplicationdevelopmenttakesahugestep
forwardinC#,givingyoumuchoftheobject-orientedpowerfoundin
theWindowssideofthedevelopmenthouse.XMLWebServices
representanewwayofconnectingtoclassesontheothersideofthe
worldthroughthebasichttpprotocol,allowingfordistributed
functionality.
Thelastthreechaptersofthebookcoveradvancedtopicssuchas
securityconcernsinthe.NETFramework,aswellas"droppingback"
totheWindowsAPIwhenthe.NETFrameworkfailstosupporta
functionrequiredforyourapplication.Youwillalsolearnhowtowork
withtheMicrosoftMobileInternetToolkit.


There'sabonuschapter,too,"WorkingwithWin32APIData,"

availableatthisbook'spageatwww.sybex.com.TousetheWin32
API,youhavetoworkwithC/C++libraries.Andthatmeans
convertingdatafromtheVisualStudio.NETmanagedenvironment
intoaformthatthelibraryfunctionswillunderstand.Thebonus
chapterexploresthespecialhandlingrequiredinamanaged
applicationforthefourlevelsofdatamanipulatedbytheWin32API:
variables,datastructures,pointers,andenumerations.Thechapter
alsodiscussesimportingresourcesfromtheunmanagedenvironment
intothemanagedapplicationenvironment.


AFewTypographicConventions
Withineachchapter,thefigures,tables,andcodelistingshaveall
beenrenumberedtomatchtheirnewchapternumbers.Forexample,
Chapter5inthisbookwasoriginallyChapter7inthebookfromwhich
itwasexcerpted,soallofthenumbershavebeenconvertedtoreflect
theChapter5numbering(forexample,Figure7.1isnowFigure5.1).
However,ifthenameofacodeelement—suchasasourcefilename,
classname,oramembername—containsanembeddedchapter
reference,thisreferencehasnotbeenmodified.Youcanseean
exampleinChapter5,whereclassnamesareExample7_4,
Example7_5,andsoon.Thesenameswereleftasis,sothatthe
sourcecodeinthebookmatchthecodeavailableat
www.sybex.com.
Thistypefaceisusedtoidentifycodeelements,InternetURLs,
andfilenamesandpaths.Boldfaceisusedtoindicatekeypartsofa
codelisting,andoccasionallykeyboardinput.Italicrepresents
placeholderssuchasfileandobject.
You'llfindthesetypesofspecialnotesthroughoutthebook:
Tip Tipstellyouaboutquickerandsmarterwaystoaccomplisha

task.TheseTipshavebeenaccumulatedbytheauthorsafter
manyhoursworkingwithC#.
Note Notesusuallyrepresentalternatewaysofaccomplishinga
taskorsomeimportantadditionalinformation.
Warning Warningsaresignificantinstructionsthatwillsaveyou
fromdisaster.WhenyouseeaWarning,dopay
attentiontoit.
You'llAlsoSeeSidebarBoxesLikeThis
Thesesectionsprovideaddedexplanationsofspecialtopicsthat
arereferredtointhesurroundingdiscussionsandthatyoumay


wanttoexploreseparatelyingreaterdetail.Theymayalsoprovide
notesonminorenhancementsthatweremadetoachapterbrought
overfromitsoriginalbook.


ForMoreInformation
VisittheCatalogattheSybexwebsite,www.sybex.com,tolearn
moreaboutallthebookscontributingtoC#Complete.That'salso
whereyou'llfindthesupportingcodeforeachsourcebook.Lookfor
theDownloadlinkonthebook'sCatalogpage.Thebonuschapteris
availablethere,too.WehopeyouenjoythisC#Completecollection
andfindituseful.


AbouttheContributors
Someofthebest—andbest-selling—Sybexauthorshavecontributed
chaptersfromtheirbookstoC#Complete.
HaroldDavisisasoftwaredevelopmentconsultantandwriter,who

hasestablishedastrongreputationforhisclearlywrittenintroductory
technicalbooks.Heistheauthorofthebest-sellingVisualBasic6:
VisualQuickStartGuidefromPeachpit,aswellasbooksonLinux,
Delphi,andwebdevelopment.Hehadapreviouscareerasa
professionalphotographer,soheisthatrarecombinationoftechie
andartist.
MikeGunderloyisaninternationallyrecognizeddatabasedeveloper,
theauthorofADOandADO.NETProgramming,andcoauthorof.NET
E-CommerceProgrammingandthebest-sellingAccess2002
Developer'sHandbook,fromSybex.Hehaswrittenmanyarticleson
MicrosoftProgrammingtopics.
A.RussellJones,Ph.D.,aconfessedformerzookeeperand
professionalmusician,nowcomposescomputerapplications.Heisa
consultantandthemanagingWebDevelopmenteditorfortheleading
websiteforprofessionaldevelopers,www.devx.com.Heisaregular
contributortoVisualStudiomagazine,andwroteSybex'sMastering
ActiveServerPages3andVisualBasicDeveloper'sGuidetoASP
andIIS.
JohnPaulMuellerisafreelanceauthorandtechnicaleditor;hehas
written53booksand200articlesonvariousprogrammingand
networkingtopics.HehaswrittenarticlesforVisualC++Developer,
VisualBasicDeveloper,andSQLServerProfessionalmagazines.He
iscurrentlytheeditorofthe.NETelectronicnewsletterforPinnacle
Publishing.
JasonPricehasmorethan10years'experienceinthesoftware
industry.HeisanMCSE,OCP,andhasextensiveexperiencewithC#,
.NET,andJava.HeistheauthorofJavaProgrammingwithOracle
SQLJ(O'Reilly).



MarkRidgewayisHeadofInformationTechnologyatKyneton
SecondaryCollegeinVictoria,Australia.Becauseofhisremote
location,hehashadacompellingreasontodiveintolearningwireless
technologies.Heisaregularcontributortooneoftheleadingwireless
applicationdevelopmentwebsites,www.anywhereyougo.com,and
hasalsowrittenforthedeveloperwebsiteDevX.com.


Chapter1:IntroductiontoVisualC#andthe
.NETFramework


Overview
Inthischapter,you'llbeintroducedtotheC#language.You'llseea
simpleexampleprogramthatdisplaysthewordsHelloWorld!onyour
computer'sscreen,alongwiththecurrentdateandtime.
You'llalsolearnaboutMicrosoft'sRapidApplicationDevelopment
(RAD)tool,VisualStudio.NET.VisualStudio.NETenablesyouto
developandrunprogramsinanintegrateddevelopmentenvironment.
ThisenvironmentusesallthegreatfeaturesofWindows,suchasthe
mouseandintuitivemenus,andincreasesyourproductivityasa
programmer.
Inthefinalsectionsofthischapter,you'llseehowtousetheextensive
documentationfromMicrosoftthatcomeswiththe.NETSoftware
DevelopmentKit(SDK)andVisualStudio.NET.You'llfindthis
documentationinvaluableasyoubecomeanexpertC#programmer.
Note BeforeyoucandevelopC#programs,you'llneedtoinstall
the.NETSDKorVisualStudio.NET.Youcandownloadthe
.NETSDKfrom
Once

you'vedownloadedtheexecutablefile,goaheadandrunit.
Followtheinstructionsonthescreentoinstallthe.NET
SDKonyourcomputer.Youcanalsopurchaseacopyof
VisualStudio.NETfromMicrosoftattheirwebsite.


DevelopingYourFirstC#Program
Learninganewprogramminglanguageissometimesadauntingtask.
Togetyoustarted,you'llbeginwithavariationontheclassic"Hello
World"program.Thisprogramtraditionallystartsallprogramming
books—andwhoarewetoarguewithtradition?
TheOriginsofthe"HelloWorld"Program
Asfarasweknow,thetraditionofthe"HelloWorld"programbeing
usedtostartprogrammingbooksbeganintheseminalworkTheC
ProgrammingLanguagebyBrianKernighanandDennisRitchie
(PrenticeHallPTR,1988).Incidentally,Cisoneofthelanguages
thatC#owesitsdevelopmentto,alongwithJavaandC++.

ThefollowingprogramdisplaysthewordsHelloWorld!onyour
computer'sscreen.Theprogramwillalsodisplaythecurrentdateand
timeretrievedfromyourcomputer.Thisprogram,showninListing1.1,
illustratesafewsimpletenetsoftheC#language.
Listing1.1:The"HelloWorld"Program

/*
Example1_1.cs:avariationontheclassic"HelloWorld!"pro
Thisprogramdisplaysthewords"HelloWorld!"onthescreen
alongwiththecurrentdateandtime.
*/


classExample1_1
{

publicstaticvoidMain()
{

//display"HelloWorld!"onthescreen
System.Console.WriteLine("HelloWorld!");



//displaythecurrentdateandtime
System.Console.WriteLine("Thecurrentdateandtimeis"+
System.DateTime.Now);
}

}

ThisprogramiscontainedinatextfilenamedExample1_1.cs.This
fileisknownasaprogramsourcefile,orsimplyasourcefile,because
itcontainsthelinesthatmakeuptheprogram.Youuseacompilerto
translateasourcefileintoanexecutablefilethatacomputercanrun;
you'lllearnmoreaboutthislaterinthe"CompilingaProgram"section.
Note Youcandownloadallthesourcefilesfortheprograms
featuredinthischapterfromtheSybexwebsiteat
.Searchforthischapter'ssource
bookbyitsISBNnumber,2911,oritstitle,MasteringVisual
C#.NET.LookfortheDownloadlinkontheright.Once
you'vedownloadedthefiles,youcanfollowalongwiththe
exampleswithouthavingtotypeintheprogramlistings.

You'llnoticethattheextensionfortheExample1_1.csfileis.cs—
thisistherecommendedextensionforC#sourcefiles.Becausethe
fileisatextfile,youcanopenandviewtheExample1_1.csfile
usingatexteditorsuchasNotepad.Goaheadandopenthefileifyou
want.
Tip YoucanalsoeditandsavesourcefilesusingNotepad,
althoughasyoudevelopmorecomplexprogramsyou'llfind
thatVisualStudio.NETisamuchmoreefficienttooltouse.
You'lllearnaboutVisualStudio.NETlaterinthischapter.
Let'sgothroughthelinesinExample1_1.cs.Thefirstfourlinesare
asfollows:
/*


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

Tải bản đầy đủ ngay
×