IntroToCSharpArticle40文档格式.docx
《IntroToCSharpArticle40文档格式.docx》由会员分享,可在线阅读,更多相关《IntroToCSharpArticle40文档格式.docx(23页珍藏版)》请在冰豆网上搜索。
C#Classes12
C#Structs16
C#Delegates&
Events17
GarbageCollection19
JavaProgrammerPointofView21
Objective-CProgrammerPointofView22
Summary23
Overview
C#(pronounced"
Csharp"
)isasimple,modern,object-oriented,andtype-safeprogramminglanguage.ItwillimmediatelybefamiliartoC/C++andJavaprogrammers.C#combinesthehighproductivityofRapidApplicationDevelopment(RAD)languagesandtherawpowerofC++.
ThisarticleintroducesC#,andcomparesittoothermodernobject-orientedlanguageslikeObjective-CandJava.
Objectives
Whenyou’vefinishedthearticle,youwillhave:
∙Ahigh-levelunderstandingoftheC#programminglanguage.
∙Ahigh-levelunderstandingofthe.NETframework.
∙AclearviewofthedifferencesandsimilaritiesintheimplementationofbasicscenariosinC#versusJavaandObjective-C.
IntroductiontoC#
C#isanobject-orientedlanguagethatenablesprogrammerstobuildquicklyawiderangeofapplicationsfortheMicrosoft®
.NETframework.ThegoalofC#andthe.NETframeworkistoshortendevelopmenttimebyfreeingthedeveloperfromworryingaboutseverallow-levelprogrammingtaskssuchasmemorymanagement,typesafetyissues,standardlibraries,arrayboundschecking,andsoon.Thisallowsdeveloperstospendthemajorityofdevelopmenttimeworkingontheirapplicationsandbusinesslogicinstead.
C#isasimple,modernobject-orientedandtype-safeprogramminglanguage.Letusseewhy.
Simple
BeingapartoftheMicrosoft.NETplatform,C#applicationsreceivesupportfromtheruntime,andtheyuseservicesprovidedbytheruntime.The.NETframeworkisamanagedenvironment:
theruntimemanagesmemoryallocation—thisfreesthedeveloperfromthattask.Programmersdonothavetodealwiththeburdenofmemorymanagementandeliminatingmemoryleaks.
C#supportsoperatoroverloading,similarlytoC++;
JavaandObjective-Cdonotsupportit.
Inheritance-relatedfeaturesareclearerandmoreprecisethaninC++:
Anabstractkeywordisusedinsteadofdeclaringpurevirtualfunctions.
Abstractclassesaredeclaredassuchdirectlybyusingtheabstractkeyword,notindirectlybylackofmethod/functionimplementation("
purevirtualfunctions"
).
Anabstractclassmaybecompletelyimplementedandyetbedeclaredabstractforarchitecturalreasons.
Anoverridekeywordisusedforoverridingavirtualmethod.
Newclassmembertypes,suchaspropertiesandindexers,areintroducedtosimplifycommontaskssuchaslistiterationandpropertygettingandsetting.
LessErrorProne
C#islesserror-pronethanC++duetothefollowingcharacteristics:
UnlikeC++,whereitispossibletodeclareanytypeofpointerandassignittoanyallocatedaddressorcastittoanyothertype,C#allowsonlytype-safecasting.Castingerrorsaredetectedateithercompiletimeoratruntime.However,ineithersituation,youwillnotmissanyerrors.
TheuseofGenerictypesallowstemplateclassestoremaintype-safeatcompiletime.Thisallowstheprogrammertodetecterrorsduringcompile,ratherthanatruntime.
RunningunderthemanagedCLR,boundscheckingisperformedformanagedarraysautomaticallywhileaccessingtheallocatedarraymemberobject.Thispreventsaccidentalmemorycorruption.
Modern
C#isdesignedtomeetmodernapplicationrequirements,aswellasintegratingmodernsoftwareconcepts:
C#,asa.NETlanguage,providesalargersetofbasictypes,includingforexampletheDecimaltypeusedtohandlefinancialapplicationscorrectly.
Knownconcepts,suchasenumeratedtypes,bitflags,first-classfunctionsandothers,becomefirst-classcitizentypeswitharichsetoffunctionalitiesthatrepresenttype-specificusagerequirements.
Itcontainsabuilt-inexception-handlingmechanism.
C#providesabuilt-ineventhandlerforsimplerhandlingofintegrated(forexample,GUIandWeb)applicationrequirements.
C#providesacompletereflectionmechanism,allowingobjectmetadatatobeexploredduringruntime.
ObjectOriented
C#supportsthethreepillarsofObject-OrientedProgramming:
Encapsulation
Aclasshastoolstohideitsimplementationdetailsandberesponsibleforitsobjects’state
Inheritance
The“isa”relationshipcanbedefinedbetweenclasses,enablingextensibilityandreusability
Polymorphism
Aprogramcanhandledifferenttypesofobjectsidentically,sharingthesamebase,havingpolymorphicbehavior,basedonspecificobjecttypes
EverythinginC#ispartofatype(forexample,class,interface,andstruct).Thereareno“global”(non-member)functionsorvariables.
Everytypeinstance“isanobject.”Alltypesarederivedfromacommonbaseclass:
object.
WhiletheseconceptsareveryfamiliartoJavadevelopers,theyarefundamentallydifferent(andinsomecasesevencompletelynew)forC/C++/Objective-Cdevelopers.
AfewwordsaboutJava
JavaisaprogramminglanguageoriginallydevelopedbyJamesGoslingatSunMicrosystemsandreleasedin1995asacorecomponentofSunMicrosystems’Javaplatform.ThelanguagederivesmuchofitssyntaxfromCandC++buthasasimplerobjectmodelandfewerlow-levelfacilities.Javaapplicationstypicallyarecompiledtobytecode(classfile)thatcanrunonanyJavaVirtualMachine(JVM)regardlessofcomputerarchitecture.Javaisgeneral-purpose,concurrent,class-based,andobject-oriented.Itisdesignedspecificallytohaveasfewimplementationdependenciesaspossible.
AfewwordsaboutObjective-C
TheObjective-Clanguageisasimplecomputerlanguagedesignedtoenablesophisticatedobject-orientedprogramming.Objective-CisdefinedasasmallbutpowerfulsetofextensionstothestandardANSIClanguage.ItispossibletocompileanyCprogramwithanObjective-Ccompiler,andtofreelyincludeCcodewithinanObjective-Cclass.ItsadditionstoCaremostlyinspiredbySmalltalk,oneofthefirstobject-orientedprogramminglanguages.Allofthesyntaxfornon-object-orientedoperations(includingprimitivevariables,preprocessing,expressions,functiondeclarations,andfunctioncalls)isidenticaltoC,whilethesyntaxforobject-orientedfeaturesisanimplementationofSmalltalk-stylemessaging.Today,Objective-CisusedprimarilyonApple'
sMacOSXandiOS:
twoenvironmentsbasedontheOpenStepstandard,thoughnotcompliantwithit.Objective-CistheprimarylanguageusedforApple'
sCocoaAPI,anditwasoriginallythemainlanguageonNeXT'
sNeXTSTEPOS.
”
Historically,allarticlesaboutprogramminglanguagesstartwitha“HelloWorld!
”sample.Thisarticlewillfollowthistradition–hereisaC#versionofthispopularprogram:
C#
usingSystem;
classHelloApp
{
staticvoidMain()
{
Console.WriteLine("
HelloC#!
"
);
}
}
Thiscodereferencesthe"
System"
namespace,whichprovidesthe"
Console"
class,declaresaclassandenclosed"
Main"
staticmethod,which,inturn,callstheConsoleclass’s"
WriteLine"
staticmethodtooutputastring.
Note:
RunningtheabovesampledirectlyunderWindowsPhone7willnotproduceanytangibleoutput,astheWindowsPhone7consoleisnotaccessible.Thecodeprovidedisonlyforcomparison.
LetusseethesameprogramwritteninJava:
Java
publicclassHelloWorld{
publicstaticvoidmain(String[]args){
System.out.println("
HelloJava!
AndnowinObjective-C:
Objective-C
#import<
stdio.h>
intmain(intargc,constchar*argv[]){
printf("
HelloObjective-C!
\n"
);
return0;
Thefirstdifferenceisincodeorganization:
whilebothC#andJavahaveaclasswithonemethod,Objective-Chasjustamethod.
Theseconddifferenceliesinthesignatureofthemethod:
inC#,the“Main”methodmuststartwithcapital“M”,whileinJavaandObjective-C,itisnotarequirement.The“String[]”argumentforthe“Main”methodinC#isoptional.
Thethirddifferenceisinthe“Main”method’sreturntype:
inC#(andJava),itreturnsvoidwhileinObjective-Citreturns“int”.InC#,theMainmethodcouldalsoreturnan“int”value.
Themoreweexaminethecodethemoredifferenceswewilldiscover.
DefiningaClass
Muchofobject-orientedprogrammingconsistsofwritingcodefornewobjects—definingnewclasses.TheclassdefinitionsinC#andJavaarefairlysimilar:
C#(andJava)
classFraction
publicintnumerator;
publicintdenominator;
publicvoidPrint()
//C#
{0}/{1}"
numerator,denominator);
//Java
//System.out.println(newPrintfFormat("
%d/%d"
).sprintf(numerator,denominator));
InObjective-C,classesaredefinedintwoparts:
1.Aninterfacethatdeclaresthemethodsandinstancevariablesoftheclassandnamesitssuperclass
2.Animplementationthatactuallydefinestheclass(containsthecodethatimplementsitsmethods)
Typically,thesearesplitbetweentwofiles,thoughsometimesaclassdefinitionmayspanseveralfilesbyusingafeaturecalleda“category.”Thesameclass/interfacewritteninObjective-C:
Foundation/NSObject.h>
@interfaceFraction:
NSObject{
intnumerator;
intdenominator;
-(void)print;
-(void)setNumerator:
(int)n;
-(void)setDenominator:
(int)d;
-(int)numerator;
-(int)denominator;
@end
#import"
Fraction.h"
@implementationFraction
-(void)print{
%i/%i"
numerator,denominator);
(int)n{
numerator=n;
(int)d{
denominator=d;
-(int)denominator{
returndenominat