ASP.NET编程:C#和VB.net语法对照图
归根到底,Java跨平台可以,但是要重新编写代码,否则还分什么J2EE/J2SE/J2ME呢!语法C#和VB.net的语法相差仍是对照年夜的.大概你会C#,大概你会VB.将它们俩放在一同对照一下你就会很快读懂,并把握另外一门言语.
信任上面这张图会对你匡助很年夜.
Comments
VB.NET
SinglelineonlyRemSinglelineonlyC#
//Singleline/*Multipleline*////XMLcommentsonsingleline/**XMLcommentsonmultiplelines*/DataTypes
VB.NET
ValueTypesBooleanByteChar(example:"A")Short,Integer,LongSingle,DoubleDecimalDateReferenceTypesObjectStringDimxAsIntegerSystem.Console.WriteLine(x.GetType())System.Console.WriteLine(TypeName(x))TypeconversionDimdAsSingle=3.5DimiAsInteger=CType(d,Integer)i=CInt(d)i=Int(d)C#
//ValueTypesboolbyte,sbytechar(example:A)short,ushort,int,uint,long,ulongfloat,doubledecimalDateTime//ReferenceTypesobjectstringintx;Console.WriteLine(x.GetType())Console.WriteLine(typeof(int))//Typeconversionfloatd=3.5;inti=(int)dConstants
VB.NET
ConstMAX_AUTHORSAsInteger=25ReadOnlyMIN_RANKAsSingle=5.00C#
constintMAX_AUTHORS=25;readonlyfloatMIN_RANKING=5.00;Enumerations
VB.NET
EnumActionStartStopisareservedwordRewindForwardEndEnumEnumStatusFlunk=50Pass=70Excel=90EndEnumDimaAsAction=Action.StopIfaAction.StartThen_Prints"Stopis1"System.Console.WriteLine(a.ToString&"is"&a)Prints70System.Console.WriteLine(Status.Pass)PrintsPassSystem.Console.WriteLine(Status.Pass.ToString())C#
enumAction{Start,Stop,Rewind,Forward};enumStatus{Flunk=50,Pass=70,Excel=90};Actiona=Action.Stop;if(a!=Action.Start)//Prints"Stopis1"System.Console.WriteLine(a+"is"+(int)a);//Prints70System.Console.WriteLine((int)Status.Pass);//PrintsPassSystem.Console.WriteLine(Status.Pass);Operators
VB.NET
Comparison=<=>=Arithmetic+-*/Mod(integerdivision)^(raisetoapower)Assignment=+=-=*=/==^=<<=>>=&=BitwiseAndAndAlsoOrOrElseNot<>LogicalAndAndAlsoOrOrElseNotStringConcatenation&C#
//Comparison==<=>=!=//Arithmetic+-*/%(mod)/(integerdivisionifbothoperandsareints)Math.Pow(x,y)//Assignment=+=-=*=/=%=&=|=^=<<=>>=++--//Bitwise&|^~<>//Logical&&||!//StringConcatenation+Choices
VB.NET
greeting=IIf(age<20,"Whatsup?","Hello")Onelinedoesntrequire"EndIf",no"Else"Iflanguage="VB.NET"ThenlangType="verbose"Use:toputtwocommandsonsamelineIfx100Andy<5Thenx*=5:y*=2PreferredIfx100Andy<5Thenx*=5y*=2EndIfortobreakupanylongsinglecommanduse_IfhenYouHaveAReally<longLineAnd_itNeedsToBeBrokenInto2>LinesThen_UseTheUnderscore(charToBreakItUp)Ifx>5Thenx*=yElseIfx=5Thenx+=yElseIfx<10Thenx-=yElsex/=yEndIfMustbeaprimitivedatatypeSelectCasecolorCase"black","red"r+=1Case"blue"b+=1Case"green"g+=1CaseElseother+=1EndSelectC#
greeting=age<20?"Whatsup?":"Hello";if(x!=100&&y<5){//Multiplestatementsmustbeenclosedin{}x*=5;y*=2;}if(x>5)x*=y;elseif(x==5)x+=y;elseif(x<10)x-=y;elsex/=y;//Mustbeintegerorstringswitch(color){case"black":case"red":r++;break;case"blue"break;case"green":g++;break;default:other++;break;}Loops
VB.NET
Pre-testLoops:Whilec<10c+=1EndWhileDoUntilc=10c+=1LoopPost-testLoop:DoWhilec<10c+=1LoopForc=2To10Step2System.Console.WriteLine(c)NextArrayorcollectionloopingDimnamesAsString()={"Steven","SuOk","Sarah"}ForEachsAsStringInnamesSystem.Console.WriteLine(s)NextC#
//Pre-testLoops:while(i<10)i++;for(i=2;i<=10;i+=2)System.Console.WriteLine(i);//Post-testLoop:doi++;while(i<10);//Arrayorcollectionloopingstring[]names={"Steven","SuOk","Sarah"};foreach(stringsinnames)System.Console.WriteLine(s);Arrays
VB.NET
Dimnums()AsInteger={1,2,3}ForiAsInteger=0Tonums.Length-1Console.WriteLine(nums(i))Next4istheindexofthelastelement,soitholds5elementsDimnames(4)AsStringnames(0)="Steven"ThrowsSystem.IndexOutOfRangeExceptionnames(5)="Sarah"Resizethearray,keepingtheexistingvalues(Preserveisoptional)ReDimPreservenames(6)DimtwoD(rows-1,cols-1)AsSingletwoD(2,0)=4.5Dimjagged()()AsInteger={_NewInteger(4){},NewInteger(1){},NewInteger(2){}}jagged(0)(4)=5C#
int[]nums={1,2,3};for(inti=0;i<nums.Length;i++)Console.WriteLine(nums);//5isthesizeofthearraystring[]names=newstring;names="Steven";//ThrowsSystem.IndexOutOfRangeExceptionnames="Sarah"//C#cantdynamicallyresizeanarray.//Justcopyintonewarray.string[]names2=newstring;//ornames.CopyTo(names2,0);Array.Copy(names,names2,names.Length);float[,]twoD=newfloat;twoD=4.5;int[][]jagged=newint[]{newint,newint,newint};jagged=5;Functions
VB.NET
Passbyvalue(in,default),reference(in/out),andreference(out)SubTestFunc(ByValxAsInteger,ByRefyAsInteger,ByRefzAsInteger)x+=1y+=1z=5EndSubcsettozerobydefaultDima=1,b=1,cAsIntegerTestFunc(a,b,c)System.Console.WriteLine("{0}{1}{2}",a,b,c)125AcceptvariablenumberofargumentsFunctionSum(ByValParamArraynumsAsInteger())AsIntegerSum=0ForEachiAsIntegerInnumsSum+=iNextEndFunctionOruseaReturnstatementlikeC#DimtotalAsInteger=Sum(4,3,2,1)returns10OptionalparametersmustbelistedlastandmusthaveadefaultvalueSubSayHello(ByValnameAsString,OptionalByValprefixAsString="")System.Console.WriteLine("Greetings,"&prefix&""&name)EndSubSayHello("Steven","Dr.")SayHello("SuOk")
C#
//Passbyvalue(in,default),reference//(in/out),andreference(out)voidTestFunc(intx,refinty,outintz){x++;y++;z=5;}inta=1,b=1,c;//cdoesntneedinitializingTestFunc(a,refb,outc);System.Console.WriteLine("{0}{1}{2}",a,b,c);//125//AcceptvariablenumberofargumentsintSum(paramsint[]nums){intsum=0;foreach(intiinnums)sum+=i;returnsum;}inttotal=Sum(4,3,2,1);//returns10/*C#doesntsupportoptionalarguments/parameters.Justcreatetwodifferentversionsofthesamefunction.*/voidSayHello(stringname,stringprefix){System.Console.WriteLine("Greetings,"
+prefix+""+name);}voidSayHello(stringname){SayHello(name,"");}ExceptionHandling
VB.NET
DeprecatedunstructurederrorhandlingOnErrorGoToMyErrorHandler...MyErrorHandler:System.Console.WriteLine(Err.Description)DimexAsNewException("Somethinghasreallygonewrong.")ThrowexTryy=0x=10/yCatchexAsExceptionWheny=0ArgumentandWhenisoptionalSystem.Console.WriteLine(ex.Message)FinallyDoSomething()EndTryC#
Exceptionup=newException("Somethingisreallywrong.");throwup;//hahatry{y=0;x=10/y;}catch(Exceptionex){//Argumentisoptional,no"When"keywordConsole.WriteLine(ex.Message);}finally{//Dosomething}Namespaces
VB.NET
NamespaceASPAlliance.DotNet.Community...EndNamespaceorNamespaceASPAllianceNamespaceDotNetNamespaceCommunity...EndNamespaceEndNamespaceEndNamespaceImportsASPAlliance.DotNet.CommunityC#
namespaceASPAlliance.DotNet.Community{...}//ornamespaceASPAlliance{namespaceDotNet{namespaceCommunity{...}}}usingASPAlliance.DotNet.Community;Classes/Interfaces
VB.NET
AccessibilitykeywordsPublicPrivateFriendProtectedProtectedFriendSharedInheritanceClassArticlesInheritsAuthors...EndClassInterfacedefinitionInterfaceIArticle...EndInterfaceExtendinganinterfaceInterfaceIArticleInheritsIAuthor...EndInterfaceInterfaceimplementation</span>ClassPublicationDateImplements</strong>IArticle,IRating...EndClassC#
//Accessibilitykeywordspublicprivateinternalprotectedprotectedinternalstatic//InheritanceclassArticles:Authors{...}//InterfacedefinitioninterfaceIArticle{...}//ExtendinganinterfaceinterfaceIArticle:IAuthor{...}//InterfaceimplementationclassPublicationDate:IArticle,IRating{...}Constructors/Destructors
VB.NET
ClassTopAuthorPrivate_topAuthorAsIntegerPublicSubNew()_topAuthor=0EndSubPublicSubNew(ByValtopAuthorAsInteger)Me._topAuthor=topAuthorEndSubProtectedOverridesSubFinalize()DesctructorcodetofreeunmanagedresourcesMyBase.Finalize()EndSubEndClassC#
classTopAuthor{privateint_topAuthor;publicTopAuthor(){_topAuthor=0;}publicTopAuthor(inttopAuthor){this._topAuthor=topAuthor}~TopAuthor(){//Destructorcodetofreeunmanagedresources.//ImplicitlycreatesaFinalizemethod}}Objects
VB.NET
DimauthorAsTopAuthor=NewTopAuthorWithauthor.Name="Steven".AuthorRanking=3EndWithauthor.Rank("Scott")author.Demote()CallingSharedmethodorTopAuthor.Rank()Dimauthor2AsTopAuthor=authorBothrefertosameobjectauthor2.Name="Joe"System.Console.WriteLine(author2.Name)PrintsJoeauthor=NothingFreetheobjectIfauthorIsNothingThen_author=NewTopAuthorDimobjAsObject=NewTopAuthorIfTypeOfobjIsTopAuthorThen_System.Console.WriteLine("IsaTopAuthorobject.")C#
TopAuthorauthor=newTopAuthor();//No"With"constructauthor.Name="Steven";author.AuthorRanking=3;author.Rank("Scott");TopAuthor.Demote()//CallingstaticmethodTopAuthorauthor2=author//Bothrefertosameobjectauthor2.Name="Joe";System.Console.WriteLine(author2.Name)//PrintsJoeauthor=null//Freetheobjectif(author==null)author=newTopAuthor();Objectobj=newTopAuthor();if(objisTopAuthor)SystConsole.WriteLine("IsaTopAuthorobject.");Structs
VB.NET
StructureAuthorRecordPublicnameAsStringPublicrankAsSinglePublicSubNew(ByValnameAsString,ByValrankAsSingle)Me.name=nameMe.rank=rankEndSubEndStructureDimauthorAsAuthorRecord=NewAuthorRecord("Steven",8.8)Dimauthor2AsAuthorRecord=authorauthor2.name="Scott"System.Console.WriteLine(author.name)PrintsStevenSystem.Console.WriteLine(author2.name)PrintsScottC#
structAuthorRecord{publicstringname;publicfloatrank;publicAuthorRecord(stringname,floatrank){this.name=name;this.rank=rank;}}AuthorRecordauthor=newAuthorRecord("Steven",8.8);AuthorRecordauthor2=authorauthor.name="Scott";SystemConsole.WriteLine(author.name);//PrintsStevenSystem.Console.WriteLine(author2.name);//PrintsScottProperties
VB.NET
Private_sizeAsIntegerPublicPropertySize()AsIntegerGetReturn_sizeEndGetSet(ByValValueAsInteger)IfValue<0Then_size=0Else_size=ValueEndIfEndSetEndPropertyfoo.Size+=1C#
privateint_size;publicintSize{get{return_size;}set{if(value<0)_size=0;else_size=value;}}foo.Size++;Delegates/Events
VB.NET
DelegateSubMsgArrivedEventHandler(ByValmessageAsString)EventMsgArrivedEventAsMsgArrivedEventHandlerortodefineaneventwhichdeclaresadelegateimplicitlyEventMsgArrivedEvent(ByValmessageAsString)AddHandlerMsgArrivedEvent,AddressOfMy_MsgArrivedCallbackWontthrowanexceptionifobjisNothingRaiseEventMsgArrivedEvent("Testmessage")RemoveHandlerMsgArrivedEvent,AddressOfMy_MsgArrivedCallbackImportsSystem.Windows.FormsWithEventscantbeusedonlocalvariableDimWithEventsMyButtonAsButtonMyButton=NewButtonPrivateSubMyButton_Click(ByValsenderAsSystem.Object,_ByValeAsSystem.EventArgs)HandlesMyButton.ClickMessageBox.Show(Me,"Buttonwasclicked","Info",_MessageBoxButtons.OK,MessageBoxIcon.Information)EndSubC#
delegatevoidMsgArrivedEventHandler(stringmessage);eventMsgArrivedEventHandlerMsgArrivedEvent;//DelegatesmustbeusedwitheventsinC#MsgArrivedEvent+=newMsgArrivedEventHandler(My_MsgArrivedEventCallback);//ThrowsexceptionifobjisnullMsgArrivedEvent("Testmessage");MsgArrivedEvent-=newMsgArrivedEventHandler(My_MsgArrivedEventCallback);usingSystem.Windows.Forms;ButtonMyButton=newButton();MyButton.Click+=newSystem.EventHandler(MyButton_Click);privatevoidMyButton_Click(objectsender,
System.EventArgse){MessageBox.Show(this,"Buttonwasclicked","Info",MessageBoxButtons.OK,MessageBoxIcon.Information);}ConsoleI/O
VB.NET
SpecialcharacterconstantsvbCrLf,vbCr,vbLf,vbNewLinevbNullStringvbTabvbBackvbFormFeedvbVerticalTab""Chr(65)ReturnsASystem.Console.Write("Whatsyourname?")DimnameAsString=System.Console.ReadLine()System.Console.Write("Howoldareyou?")DimageAsInteger=Val(System.Console.ReadLine())System.Console.WriteLine("{0}is{1}yearsold.",name,age)orSystem.Console.WriteLine(name&"is"&age&"yearsold.")DimcAsIntegerc=System.Console.Read()ReadsinglecharSystem.Console.WriteLine(c)Prints65ifuserenters"A"C#
//Escapesequencesn,rtConvert.ToChar(65)
//ReturnsA-equivalenttoChr(num)inVB//or(char)65System.Console.Write("Whatsyourname?");stringname=SYstem.Console.ReadLine();System.Console.Write("Howoldareyou?");intage=Convert.ToInt32(System.Console.ReadLine());System.Console.WriteLine("{0}is{1}yearsold.",
name,age);//orSystem.Console.WriteLine(name+"is"+
age+"yearsold.");intc=System.Console.Read();//ReadsinglecharSystem.Console.WriteLine(c);
//Prints65ifuserenters"A"FileI/O
VB.NET
ImportsSystem.IOWriteouttotextfileDimwriterAsStreamWriter=File.CreateText("c:myfile.txt")writer.WriteLine("Outtofile.")writer.Close()ReadalllinesfromtextfileDimreaderAsStreamReader=File.OpenText("c:myfile.txt")DimlineAsString=reader.ReadLine()WhileNotlineIsNothingConsole.WriteLine(line)line=reader.ReadLine()EndWhilereader.Close()WriteouttobinaryfileDimstrAsString="Textdata"DimnumAsInteger=123DimbinWriterAsNewBinaryWriter(File.OpenWrite("c:myfile.dat"))binWriter.Write(str)binWriter.Write(num)binWriter.Close()ReadfrombinaryfileDimbinReaderAsNewBinaryReader(File.OpenRead("c:myfile.dat"))str=binReader.ReadString()num=binReader.ReadInt32()binReader.Close()C#
usingSystem.IO;//WriteouttotextfileStreamWriterwriter=File.CreateText("c:myfile.txt");writer.WriteLine("Outtofile.");writer.Close();//ReadalllinesfromtextfileStreamReaderreader=File.OpenText("c:myfile.txt");stringline=reader.ReadLine();while(line!=null){Console.WriteLine(line);line=reader.ReadLine();}reader.Close();//Writeouttobinaryfilestringstr="Textdata";intnum=123;BinaryWriterbinWriter=newBinaryWriter(File.OpenWrite("c:myfile.dat"));binWriter.Write(str);binWriter.Write(num);binWriter.Close();//ReadfrombinaryfileBinaryReaderbinReader=newBinaryReader(File.OpenRead("c:myfile.dat"));str=binReader.ReadString();num=binReader.ReadInt32();binReader.Close();那做企业软件是不是最好用J2EE? 它可通过内置的组件实现更强大的功能,如使用A-DO可以轻松地访问数据库。 平台无关性是PHP的最大优点,但是在优点的背后,还是有一些小小的缺点的。如果在PHP中不使用ODBC,而用其自带的数据库函数(这样的效率要比使用ODBC高)来连接数据库的话,使用不同的数据库,PHP的函数名不能统一。这样,使得程序的移植变得有些麻烦。不过,作为目前应用最为广泛的一种后台语言,PHP的优点还是异常明显的。 大哥拜托,Java在95年就出来了,微软垄断个妹啊,服务器市场微软完全是后后来者,当年都是Unix的市场,现在被WindowsServer和Linux抢下大片,包括数据库也一样。 ASP.Net和ASP的最大区别在于编程思维的转换,而不仅仅在于功能的增强。ASP使用VBS/JS这样的脚本语言混合html来编程,而那些脚本语言属于弱类型、面向结构的编程语言,而非面向对象。 ASP在执行的时候,是由IIS调用程序引擎,解释执行嵌在HTML中的ASP代码,最终将结果和原来的HTML一同送往客户端。 Servlet却在响应第一个请求的时候被载入,一旦Servlet被载入,便处于已执行状态。对于以后其他用户的请求,它并不打开进程,而是打开一个线程(Thread),将结果发送给客户。由于线程与线程之间可以通过生成自己的父线程(ParentThread)来实现资源共享,这样就减轻了服务器的负担,所以,JavaServlet可以用来做大规模的应用服务。 主流网站开发语言之CGI:CGI就是公共网关接口(CommonGatewayInterface)的缩写。它是最早被用来建立动态网站的后台技术。这种技术可以使用各种语言来编写后台程序,例如C,C++,Java,Pascal等。 使用普通的文本编辑器编写,如记事本就可以完成。由脚本在服务器上而不是客户端运行,ASP所使用的脚本语言都在服务端上运行,用户端的浏览器不需要提供任何别的支持,这样大提高了用户与服务器之间的交互的速度。
页:
[1]