IntroToCSharpArticle40文档格式.docx

上传人:b****5 文档编号:18837473 上传时间: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

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

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

当前位置:首页 > 自然科学 > 数学

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

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