您的位置:首页 > 编程语言 > C语言/C++

C# FAQ for C++ programmers

2005-08-12 10:53 501 查看
1.WhatisC#?[Introduction]

C#isaprogramminglanguagedesignedbyMicrosoft.ItislooselybasedonC/C++,andbearsastrikingsimilaritytoJava.MicrosoftdescribeC#asfollows:
"C#isasimple,modern,objectoriented,andtype-safeprogramminglanguagederivedfromCandC++.C#(pronounced'Csharp')isfirmlyplantedintheCandC++familytreeoflanguages,andwillimmediatelybefamiliartoCandC++programmers.C#aimstocombinethehighproductivityofVisualBasicandtherawpowerofC++."

2.HowdoIdevelopC#apps?[Introduction]

The(free).NETSDKcontainstheC#command-linecompiler(csc.exe).VisualStudiohasfullyintegratedsupportforC#development.OnLinuxyoucanuseMono.

3.DoesC#replaceC++?[Introduction]

TherearethreeoptionsopentotheWindowsdeveloperfromaC++background:
----StickwithstandardC++.Don'tuse.NETatall.
----UseC++with.NET.Microsoftsupplya.NETC++compilerthatproducesILratherthanmachinecode.Howevertomakefulluseofthe.NETenvironment(e.g.garbagecollection),asetofextensionsarerequiredtostandardC++.In.NET1.xthisextendedlanguageiscalledManagedExtensionsforC++.In.NET2.0MEC++hasbeencompletelyredesignedunderthestewardshipofStanLippman,andrenamedC++/CLI.
----ForgetC++anduseC#.
Eachoftheseoptionshasmerits,dependingonthedeveloperandtheapplication.Formyownpart,IintendtouseC#wherepossible,fallingbacktoC++onlywherenecessary.MEC++(soontobeC++/CLI)isveryusefulforinteropbetweennew.NETcodeandoldC++code-simplywriteamanagedwrapperclassusingMEC++,thenusethemanagedclassfromC#.Fromexperience,thisworkswell.

4.DoesC#haveitsownclasslibrary?[Introduction]

Notexactly.The.NETFrameworkhasacomprehensiveclasslibrary,whichC#canmakeuseof.C#doesnothaveitsownclasslibrary.

5.WhatstandardtypesdoesC#use?[Types]

C#supportsaverysimilarrangeofbasictypestoC++,includingint,long,float,double,char,string,arrays,structsandclasses.However,don'tassumetoomuch.Thenamesmaybefamiliar,butmanyofthedetailsaredifferent.Forexample,alongis64bitsinC#,whereasinC++thesizeofalongdependsontheplatform(typically32bitsona32-bitplatform,64bitsona64-bitplatform).AlsoclassesandstructsarealmostthesameinC++-thisisnottrueforC#.Finally,charsandstringsin.NETare16-bit(Unicode/UTF-16),not8-bitlikeC++.
Furthermore,thesesimplebuilt-intypesarejustaliasestotheaccording.NetFrameworkclasses.Forinstance,boolforSystem.Boolean,charforSystem.Char,intforSystem.Int32,floatforSystem.Single,doubleforSystem.DoubleandlongforSystem.Int64

6.IsittruethatallC#typesderivefromacommonbaseclass?[Types]

Yesandno.Alltypescanbetreatedasiftheyderivefromobject(System.Object),butinordertotreataninstanceofavaluetype(e.g.int,float)asobject-derived,theinstancemustbeconvertedtoareferencetypeusingaprocesscalled'boxing'.Intheoryadevelopercanforgetaboutthisandlettherun-timeworryaboutwhentheconversionisnecessary,butinrealitythisimplicitconversioncanhaveside-effectsthatmaytripuptheunwary.

7.SoIcanpassaninstanceofavaluetypetoamethodthattakesanobjectasaparameter?[Types]

Yes.Forexample:
classCApplication
{
publicstaticvoidMain()
{
intx=25;
strings="fred";
DisplayMe(x);
DisplayMe(s);
}
staticvoidDisplayMe(objecto)
{
System.Console.WriteLine("Youare{0}",o);
}
}

Thiswoulddisplay:
Youare25
Youarefred

8.Whatarethefundamentaldifferencesbetweenvaluetypesandreferencetypes?[Types]

C#dividestypesintotwocategories-valuetypesandreferencetypes.Mostoftheintrinsictypes(e.g.int,char)arevaluetypes.Structsarealsovaluetypes.Referencetypesincludeclasses,arraysandstrings.Thebasicideaisstraightforward-aninstanceofavaluetyperepresentstheactualdata,whereasaninstanceofareferencetyperepresentsapointerorreferencetothedata.
ThemostconfusingaspectofthisforC++developersisthatC#haspredeterminedwhichtypesarerepresentedasvalues,andwhicharerepresentedasreferences.AC++developerexpectstotakeresponsibilityforthisdecision.Forexample,inC++wecandothis:
intx1=3;//x1isavalueonthestack
int*x2=newint(3)//x2isapointertoavalueontheheap

butinC#thereisnocontrol:
intx1=3;//x1isavalueonthestack
intx2=newint();
x2=3;//x2isalsoavalueonthestack!

9.Okay,soanintisavaluetype,andaclassisareferencetype.Howcanintbederivedfromobject?[Types]

Itisn't,really.Whenanintisbeingusedasanint,itisavalue.However,whenitisbeingusedasanobject,itisareferencetoanintegervalue(onthemanagedheap).Inotherwords,whenyoutreatanintasanobject,theruntimeautomaticallyconvertstheintvaluetoanobjectreference.Thisprocessiscalledboxing.Theconversioninvolvescopyingtheinttotheheap,andcreatinganobjectinstancewhichreferstoit.Unboxingisthereverseprocess-theobjectisconvertedbacktoavalue.
intx=3;//newintvalue3onthestack
objectobjx=x;//newintonheap,settovalue3-stillhavex=3onstack
inty=(int)objx;//newvalue3onstack,stillgotx=3onstackandobjx=3onheap

10.AreC#referencesthesameasC++references?[Types]

Notquite.Thebasicideaisthesame,butonesignificantdifferenceisthatC#referencescanbenull.SoyoucannotrelyonaC#referencepointingtoavalidobject.InthatrespectaC#referenceismorelikeaC++pointerthanaC++reference.Ifyoutrytouseanullreference,aNullReferenceExceptionisthrown.Forexample,lookatthefollowingmethod:
voiddisplayStringLength(strings)
{
Console.WriteLine("Stringislength{0}",s.Length);
}

TheproblemwiththismethodisthatitwillthrowaNullReferenceExceptionifcalledlikethis:
strings=null;
displayStringLength(s);

OfcourseforsomesituationsyoumaydeemaNullReferenceExceptiontobeaperfectlyacceptableoutcome,butinthiscaseitmightbebettertore-writethemethodlikethis:
voiddisplayStringLength(strings)
{
if(s==null)
Console.WriteLine("Stringisnull");
else
Console.WriteLine("Stringislength{0}",s.Length);
}

文章来源:http://spaces.msn.com/members/Grisson/Blog/cns!1pdzVqmOhs8O_w1Y7GbtnyFQ!185.entry
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: