Quick C#.docx

上传人:b****9 文档编号:25152461 上传时间:2023-06-05 格式:DOCX 页数:30 大小:24.67KB
下载 相关 举报
Quick C#.docx_第1页
第1页 / 共30页
Quick C#.docx_第2页
第2页 / 共30页
Quick C#.docx_第3页
第3页 / 共30页
Quick C#.docx_第4页
第4页 / 共30页
Quick C#.docx_第5页
第5页 / 共30页
点击查看更多>>
下载资源
资源描述

Quick C#.docx

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

Quick C#.docx

QuickC#

QuickC#

LearnC#inlessthananhour.DiscovertheC#languageconstructsandfeaturesinabriefyetcomprehensivewayusingcodeexamples.ThisarticleisespeciallygoodifyouknowC++andfeellazyaboutlearningC#!

Introduction

C#isalanguagewiththefeaturesofC++,programmingstylelikeJavaandrapidapplicationmodelofBASIC.IfyoualreadyknowtheC++language,itwilltakeyoulessthananhourtoquicklygothroughthesyntaxofC#.FamiliaritywithJavawillbeaplus,asJavaprogramstructure,theconceptofpackagesandgarbagecollectionwilldefinitelyhelpyoulearnC#morequickly.SowhilediscussingC#languageconstructs,Iwillassume,youknowC++.

ThisarticlediscussestheC#languageconstructsandfeaturesusingcodeexamples,inabriefandcomprehensiveway,sothatyoujustbyhavingaglanceatthecode,canunderstandtheconcepts.

Note:

ThisarticleisnotforC#gurus.Theremustbesomeotherbeginner'sarticlesonC#,butthisisyetanotherone.

FollowingtopicsofC#languagearediscussed:

ØProgramstructure

ØNamespaces

ØDatatypes

ØVariables

ØOperatorsandexpressions

ØEnumerations

ØStatements

ØClassesandstructs

ØModifiers

ØProperties

ØInterfaces

ØFunctionparameters

ØArrays

ØIndexers

ØBoxingandunboxing

ØDelegates

ØInheritanceandpolymorphism

Followingarenotdiscussed:

ØThingswhicharecommoninC++andC#.

ØConceptslikegarbagecollection,threading,fileprocessingetc.

ØDatatypeconversions

ØExceptionhandling

Ø.NETlibrary

Programstructure

LikeC++,C#iscase-sensitive.Semicolon(;)isthestatementseparator.UnlikeC++,therearenoseparatedeclaration(header)andimplementation(CPP)filesinC#.Allcode(classdeclarationandimplementation)isplacedinonefilewithextension cs.

HavealookatthisHelloworldprograminC#.

usingSystem;

namespaceMyNameSpace

{

classHelloWorld

{

staticvoidMain(string[]args)

{

Console.WriteLine("HelloWorld");

}

}

}

EverythinginC#ispackedintoaclassandclassesinC#arepackedintonamespaces(justlikefilesinafolder).LikeC++,amainmethodistheentrypointofyourprogram.C++'smainfunctioniscalled main whereasC#'smainfunctionstartswithcapitalMandisnamedas Main.

Noneedtoputasemicolonafteraclassblockor struct definition.ItwasinC++,C#doesn'trequirethat.

Namespace

Everyclassispackagedintoanamespace.NamespacesareexactlythesameconceptasinC++,butinC#weusenamespacesmorefrequentlythaninC++.Youcanaccessaclassinanamespaceusingdot(.)qualifier.MyNameSpace isthenamespaceinhelloworldprogramabove.

Nowconsideryouwanttoaccessthe HelloWorld classfromsomeotherclassinsomeothernamespace.

usingSystem;

namespaceAnotherNameSpace

{

classAnotherClass

{

publicvoidFunc()

{

Console.WriteLine("HelloWorld");

}

}

}

Nowfromyour HelloWorld classyoucanaccessitas:

usingSystem;

usingAnotherNameSpace;//youwilladdthisusingstatement

namespaceMyNameSpace

{

classHelloWorld

{

staticvoidMain(string[]args)

{

AnotherClassobj=newAnotherClass();

obj.Func();

}

}

}

In.NETlibrary, System isthetoplevelnamespaceinwhichothernamespacesexist.Bydefaultthereexistsaglobalnamespace,soaclassdefinedoutsideanamespacegoesdirectlyintothisglobalnamespaceandhenceyoucanaccessthisclasswithoutanyqualifier.

Youcanalsodefinenestednamespaces.

Using

The #include directiveisreplacedwith using keyword,whichisfollowedbyanamespacename.Justas usingSystem asabove. System isthebaselevelnamespaceinwhichallothernamespacesandclassesarepacked.Thebaseclassforallobjectsis Object inthe System namespace.

Variables

VariablesinC#arealmostthesameasinC++exceptforthesedifferences:

ØVariablesinC#(unlikeC++),alwaysneedtobeinitializedbeforeyouaccessthem,otherwiseyouwillgetcompiletimeerror.Hence,it'simpossibletoaccessanun-initializedvariable.

ØYoucan'taccessa“dangling”pointerinC#.

ØAnexpressionthatindexesanarraybeyonditsboundsisalsonotaccessible.

ØThereare noglobalvariables orfunctionsinC#andthebehaviorofglobalsisachievedthroughstaticfunctionsandstaticvariables.

Datatypes

AlltypesofC#arederivedfromabaseclass object.Therearetwotypesofdatatypes:

ØBasic/built-intypes

ØUser-definedtypes

Followingisatablewhichlistsbuilt-inC#types:

Type

Bytes

Description

byte

1

unsignedbyte

sbyte

1

signedbyte

short

2

signedshort

ushort

2

unsignedshort

int

4

signedinteger

uint

4

unsignedinteger

long

8

signedlong

ulong

8

unsignedlong

float

4

floatingpointnumber

double

8

doubleprecisionnumber

decimal

8

fixedprecisionnumber

string

Unicodestring

char

Unicodechar

bool

true, false

boolean

Note:

TyperangeinC#andC++aredifferent,example,longinC++is4bytes,andinC#itis8bytes.Alsothebool and string typesaredifferentthanthoseinC++. bool acceptsonly true and false andnotanyinteger.

Userdefinedtypesincludes:

ØClasses

ØStructs

ØInterfaces

Memoryallocationofthedatatypesdividesthemintotwotypes:

ØValuetypes

ØReferencetypes

Valuetypes

Valuestypesarethosedatatypeswhichareallocatedinstack.Theyinclude:

ØAllbasicorbuilt-intypesexcept strings

ØStructs

ØEnum types

Referencetypes

Referencetypesareallocatedonheapandaregarbagecollectedwhentheyarenolongerbeingused.Theyarecreatedusing new operator,andthereisno delete operatorforthesetypesunlikeC++whereuserhastoexplicitlydeletethetypescreatedusing delete operator.InC#,theyareautomaticallycollectedbygarbagecollector.

Referencetypesinclude:

ØClasses

ØInterfaces

ØCollectiontypeslike Arrays

ØString

Enumeration

EnumerationsinC#areexactlylikeC++.Definedthroughakeyword enum.

Example:

enumWeekdays

{

Saturday,Sunday,Monday,Tuesday,Wednesday,Thursday,Friday

}

Classesandstructs

Classesand structsaresameasinC++,exceptthedifferenceoftheirmemoryallocation.Objectsofclassesareallocatedinheap,andarecreatedusing new,whereas structsareallocatedinstack. StructsinC#areverylightandfastdatatypes.Forheavydatatypes,youshouldcreateclasses.

Examples:

structDate

{

intday;

intmonth;

intyear;

}

classDate

{

intday;

intmonth;

intyear;

stringweekday;

stringmonthName;

publicintGetDay()

{

returnday;

}

publicintGetMonth()

{

returnmonth;

}

publicintGetYear()

{

returnyear;

}

publicvoidSetDay(intDay)

{

day=Day;

}

publicvoidSetMonth(intMonth)

{

month=Month;

}

publicvoidSetYear(intYear)

{

year=Year;

}

publicboolIsLeapYear()

{

return(year/4==0);

}

publicvoidSetDate(intday,intmonth,intyear)

{

}

...

}

Properties

IfyouarefamiliarwiththeobjectorientedwayofC++,youmusthaveanideaofproperties.Propertiesinaboveexampleof Date classare day, month and year forwhichinC++,youwrite Get and Set methods.C#providesamoreconvenient,simpleandstraightforwardwayofaccessingproperties.

Soaboveclasscanbewrittenas:

usingSystem;

classDate

{

publicintDay{

get{

returnday;

}

set{

day=value;

}

}

intday;

publicintMonth{

get{

returnmonth;

}

set{

month=value;

}

}

intmonth;

publicintYear{

get{

returnyear;

}

set{

year=value;

}

}

intyear;

publicboolIsLeapYear(intyear)

{

returnyear%4==0?

true:

false;

}

publicvoidSetDate(intday,intmonth,intyear)

{

this.day=day;

this.month=month;

this.year=year;

}

}

Hereisthewayyouwillgetandsettheseproperties:

classUser

{

publicstaticvoidMain()

{

Datedate=newDate();

date.Day=27;

date.Month=6;

date.Year=2003;

Console.WriteLine

("Date:

{0}/{1}/{2}",date.Day,date.Month,date.Year);

}

}

Modifiers

Youmustbeawareof public, private and protected modifiersthatarecommonlyusedinC++.IwillherediscusssomenewmodifiersintroducedbyC#.

readonly

readonly modifierisusedonlyfortheclassdatamembers.Asthenameindicates,the readonly datamemberscanonlyberead,oncetheyarewritteneitherbydirectlyinitializingthemorassigningvaluestotheminconstructor.Thedifferencebetweenthe readonly and const datamembersisthat const requiresyoutoinitializewiththedeclaration,thatisdirectly.Seeexamplecode:

classMyClass

{

constintconstInt=100;//directly

readonlyintmyInt=5;//directly

readonlyintmyInt2;

publicMyClass()

{

myInt2=8;//Indirectly

}

publicFunc()

{

myInt=7;//Illegal

Console.WriteLine(myInt2.ToString());

}

}

sealed

sealed modifierwithaclassdon'tletyouderiveanyclassfromit.Soyouusethis sealed keywordfortheclasseswhichyoudon'twanttobeinheritedfrom.

sealedclassCanNotbeTheParent

{

inta=5;

}

unsafe

YoucandefineanunsafecontextinC#using unsafe modifier.Inunsafecontext,youcanwriteanunsafecode,example:

C++pointersetc.Seethefollowingcode:

publicunsafeMyFunction(int*pInt,double*pDouble)

{

int*pAnotherInt=newint;

*pAnotherInt=10;

pInt=pAnotherInt;

...

*pDouble=8.9;

}

Interfaces

IfyouhaveanideaofCOM,youwillimmediatelyknowwhatIamtalkingabout.An interface istheabstractbaseclasscontainingonlythefunctionsignatureswhoseimplementationisprovidedbythechildclass.InC#,youdefinesuchclassesasinterfacesusingthe interface keyword..NETisbasedonsuchinterfaces.InC#,whereyoucan'tusemultipleclassinheritance,whi

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

当前位置:首页 > 工程科技 > 能源化工

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

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