Quick C#.docx
- 文档编号:25152461
- 上传时间:2023-06-05
- 格式:DOCX
- 页数:30
- 大小:24.67KB
Quick C#.docx
《Quick C#.docx》由会员分享,可在线阅读,更多相关《Quick C#.docx(30页珍藏版)》请在冰豆网上搜索。
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
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Quick C#
![提示](https://static.bdocx.com/images/bang_tan.gif)