IntroToCSharpArticle40.docx

上传人:b****5 文档编号:5850425 上传时间:2023-01-01 格式:DOCX 页数:23 大小:31.56KB
下载 相关 举报
IntroToCSharpArticle40.docx_第1页
第1页 / 共23页
IntroToCSharpArticle40.docx_第2页
第2页 / 共23页
IntroToCSharpArticle40.docx_第3页
第3页 / 共23页
IntroToCSharpArticle40.docx_第4页
第4页 / 共23页
IntroToCSharpArticle40.docx_第5页
第5页 / 共23页
点击查看更多>>
下载资源
资源描述

IntroToCSharpArticle40.docx

《IntroToCSharpArticle40.docx》由会员分享,可在线阅读,更多相关《IntroToCSharpArticle40.docx(23页珍藏版)》请在冰豆网上搜索。

IntroToCSharpArticle40.docx

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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 人文社科 > 文化宗教

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1