IntroToCSharpArticle40.docx
《IntroToCSharpArticle40.docx》由会员分享,可在线阅读,更多相关《IntroToCSharpArticle40.docx(23页珍藏版)》请在冰豆网上搜索。
IntroToCSharpArticle40
Article
IntrotoC#(vs.Objective-CandJava)
Documentversion:
1.0.0
Lastupdated:
10/31/2018
Contents
Overview3
Objectives3
IntroductiontoC#3
“HelloC#!
”6
.NETRuntime9
.NETandC#ProgramBasics10
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.
“HelloC#!
”
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
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#
Console.WriteLine("{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:
Objective-C
#import
@interfaceFraction:
NSObject{
intnumerator;
intdenominator;
}
-(void)print;
-(void)setNumerator:
(int)n;
-(void)setDenominator:
(int)d;
-(int)numerator;
-(int)denominator;
@end
Objective-C
#import"Fraction.h"
#import
@implementationFraction
-(void)print{
printf("%i/%i",numerator,denominator);
}
-(void)setNumerator:
(int)n{
numerator=n;
}
-(void)setDenominator:
(int)d{
denominator=d;
}
-(int)denominator{
returndenominat