|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
归根到底,Java跨平台可以,但是要重新编写代码,否则还分什么J2EE/J2SE/J2ME呢!语法C#和VB.net的语法相差仍是对照年夜的.大概你会C#,大概你会VB.
将它们俩放在一同对照一下你就会很快读懂,并把握另外一门言语.
信任上面这张图会对你匡助很年夜.
Comments
VB.NET- SinglelineonlyRemSinglelineonly
复制代码 C#- //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)d
复制代码Constants
VB.NET- ConstMAX_AUTHORSAsInteger=25ReadOnlyMIN_RANKAsSingle=5.00
复制代码 C#- constintMAX_AUTHORS=25;readonlyfloatMIN_RANKING=5.00;
复制代码Enumerations
VB.NET- EnumActionStartStopisareservedword[Stop]RewindForwardEndEnumEnumStatusFlunk=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+=1EndSelect
复制代码 C#- 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)Next
复制代码 C#- //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)=5
复制代码 C#- int[]nums={1,2,3};for(inti=0;i<nums.Length;i++)Console.WriteLine(nums[i]);//5isthesizeofthearraystring[]names=newstring[5];names[0]="Steven";//ThrowsSystem.IndexOutOfRangeExceptionnames[5]="Sarah"//C#cantdynamicallyresizeanarray.//Justcopyintonewarray.string[]names2=newstring[7];//ornames.CopyTo(names2,0);Array.Copy(names,names2,names.Length);float[,]twoD=newfloat[rows,cols];twoD[2,0]=4.5;int[][]jagged=newint[3][]{newint[5],newint[2],newint[3]};jagged[0][4]=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()EndTry
复制代码 C#
- 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.Community
复制代码 C#- namespaceASPAlliance.DotNet.Community{...}//ornamespaceASPAlliance{namespaceDotNet{namespaceCommunity{...}}}usingASPAlliance.DotNet.Community;
复制代码Classes/Interfaces
VB.NET- AccessibilitykeywordsPublicPrivateFriendProtectedProtectedFriendSharedInheritanceClassArticlesInheritsAuthors...EndClassInterfacedefinitionInterfaceIArticle...EndInterfaceExtendinganinterfaceInterfaceIArticleInheritsIAuthor...EndInterfaceInterfaceimplementation</span>ClassPublicationDateImplements</strong>IArticle,IRating...EndClass
复制代码 C#- //Accessibilitykeywordspublicprivateinternalprotectedprotectedinternalstatic//InheritanceclassArticles:Authors{...}//InterfacedefinitioninterfaceIArticle{...}//ExtendinganinterfaceinterfaceIArticle:IAuthor{...}//InterfaceimplementationclassPublicationDate:IArticle,IRating{...}
复制代码Constructors/Destructors
VB.NET- ClassTopAuthorPrivate_topAuthorAsIntegerPublicSubNew()_topAuthor=0EndSubPublicSubNew(ByValtopAuthorAsInteger)Me._topAuthor=topAuthorEndSubProtectedOverridesSubFinalize()DesctructorcodetofreeunmanagedresourcesMyBase.Finalize()EndSubEndClass
复制代码 C#- 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)PrintsScott
复制代码 C#- 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);//PrintsScott
复制代码Properties
VB.NET- Private_sizeAsIntegerPublicPropertySize()AsIntegerGetReturn_sizeEndGetSet(ByValValueAsInteger)IfValue<0Then_size=0Else_size=ValueEndIfEndSetEndPropertyfoo.Size+=1
复制代码 C#- 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)EndSub
复制代码 C#- 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? |
|