C# FAQ for C++ programmers
2005-08-12 10:53
507 查看
1.WhatisC#?[Introduction]C#isaprogramminglanguagedesignedbyMicrosoft.ItislooselybasedonC/C++,andbearsastrikingsimilaritytoJava.MicrosoftdescribeC#asfollows:
TherearethreeoptionsopentotheWindowsdeveloperfromaC++background:
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++.
Thiswoulddisplay:
ThemostconfusingaspectofthisforC++developersisthatC#haspredeterminedwhichtypesarerepresentedasvalues,andwhicharerepresentedasreferences.AC++developerexpectstotakeresponsibilityforthisdecision.Forexample,inC++wecandothis:
butinC#thereisnocontrol:
TheproblemwiththismethodisthatitwillthrowaNullReferenceExceptionifcalledlikethis:
OfcourseforsomesituationsyoumaydeemaNullReferenceExceptiontobeaperfectlyacceptableoutcome,butinthiscaseitmightbebettertore-writethemethodlikethis:
文章来源:http://spaces.msn.com/members/Grisson/Blog/cns!1pdzVqmOhs8O_w1Y7GbtnyFQ!185.entry
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);
}
相关文章推荐
- Delphi for C++ Programmers
- Objective-C for C++ Programmers
- 一个整理的比较好的关于C++程序员的问题集-The Best Questions for Would-be C++ Programmers-来至topCoder
- Robocode for c++ or c# learner ?
- 二、C++迭代器的两种实现方式 (Range for和C#、Java中的foreach)
- RAII is a must know technique for c++ programmers (zz)
- 写给C++程序员的C# FAQ
- From C++ to Objective-C: A quick guide for practical programmers
- Python中的for与其他类C语言的比较(如c++,c#)
- Singly Linked List & Destructor - C++ for C Programmers 3.4
- C++ for Business Programmers
- Expert Visual C++/CLI: .NET for Visual C++ Programmers
- A Free , Fast and Small Automatic Formatter for C , C++ , C# , Java Source Codes
- TCP/IP Sockets in C#: Practical Guide for Programmers
- 15 Essential Compilers and IDEs for C/C++ Programmers
- 一个带有Kruskal、Prim、Dijkstra算法的图类型 - C++ for C Programmers
- The Best Questions for Would-be C++ Programmers, Part 1
- Dijkstra's Shortest Path - C++ for C Programmers 2.5
- The Best Interview Questions for Would-be C++ Programmers
- 给C++程序员的Python初学指南 / Guide to Python for C++ Programmers