VB和c语法对照.docx

上传人:b****4 文档编号:24798594 上传时间:2023-06-01 格式:DOCX 页数:14 大小:24.55KB
下载 相关 举报
VB和c语法对照.docx_第1页
第1页 / 共14页
VB和c语法对照.docx_第2页
第2页 / 共14页
VB和c语法对照.docx_第3页
第3页 / 共14页
VB和c语法对照.docx_第4页
第4页 / 共14页
VB和c语法对照.docx_第5页
第5页 / 共14页
点击查看更多>>
下载资源
资源描述

VB和c语法对照.docx

《VB和c语法对照.docx》由会员分享,可在线阅读,更多相关《VB和c语法对照.docx(14页珍藏版)》请在冰豆网上搜索。

VB和c语法对照.docx

VB和c语法对照

VB.NET

ProgramStructure

C#

ImportsSystem

NamespaceHello

  ClassHelloWorld

     OverloadsSharedSubMain(ByValargs()AsString)

        DimnameAsString="VB.NET"

        'Seeifanargumentwaspassed fromthecommandline

         Ifargs.Length=1Thenname=args(0)

         Console.WriteLine("Hello,"&name&"!

")

     EndSub

  EndClass

EndNamespace

usingSystem;

namespaceHello{

  publicclassHelloWorld{

     publicstaticvoidMain(string[]args){

        stringname="C#";

       //Seeifanargumentwaspassedfromthecommandline

       if(args.Length==1)

          name=args[0];

       Console.WriteLine("Hello,"+name+"!

");

     }

  }

}

VB.NET

Comments

C#

'Singlelineonly

REM Singlelineonly

'''

XMLcomments

//Singleline

/*Multiple

   line */

///

XMLcommentsonsingleline

/**

XMLcommentsonmultiplelines*/

VB.NET

DataTypes

C#

ValueTypes

Boolean

Byte,SByte

Char

Short,UShort,Integer,UInteger,Long,ULong

Single,Double

Decimal

Date

ReferenceTypes

Object

String

Initializing

DimcorrectAsBoolean=True

DimbAsByte=&H2A 'hex

DimoAsByte=&O52 'octal

DimpersonAsObject=Nothing

DimnameAsString="Dwight"

DimgradeAsChar="B"c

DimtodayAsDate=#12/31/200712:

15:

00PM#

DimamountAsDecimal=35.99@

DimgpaAsSingle=2.9!

DimpiAsDouble=3.14159265

DimlTotalAsLong=123456L

DimsTotalAsShort=123S

DimusTotalAsUShort=123US

DimuiTotalAsUInteger=123UI

DimulTotalAsULong=123UL

TypeInformation

DimxAsInteger

Console.WriteLine(x.GetType())     ' PrintsSystem.Int32

Console.WriteLine(GetType(Integer)) 'PrintsSystem.Int32

Console.WriteLine(TypeName(x))    'PrintsInteger

TypeConversion

DimdAsSingle=3.5

DimiAsInteger=CType(d,Integer)  'setto4(Banker'srounding)

i=CInt(d) 'sameresultasCType

i=Int(d)   'setto3(Intfunctiontruncatesthedecimal)

ValueTypes

bool

byte,sbyte

char

short,ushort,int,uint,long,ulong

float, double

decimal

DateTime  (notabuilt-inC# type)

ReferenceTypes

object

string

Initializing

boolcorrect=true;

byteb=0x2A; //hex

objectperson=null;

stringname="Dwight";

chargrade='B';

DateTimetoday=DateTime.Parse("12/31/200712:

15:

00");

decimalamount=35.99m;

floatgpa=2.9f;

doublepi=3.14159265;

longlTotal=123456L;

shortsTotal=123;

ushortusTotal=123;

uintuiTotal=123;

ulongulTotal=123;

TypeInformation

intx;

Console.WriteLine(x.GetType());        //PrintsSystem.Int32

Console.WriteLine(typeof(int));        //PrintsSystem.Int32

Console.WriteLine(x.GetType().Name); //printsInt32

TypeConversion

floatd=3.5f;

inti=(int)d;  //setto 3 (truncatesdecimal)

VB.NET

Constants

C#

Const MAX_STUDENTSAsInteger=25

'Cansettoaconstor var;maybeinitializedinaconstructor

ReadOnlyMIN_DIAMETERAsSingle=4.93

constintMAX_STUDENTS=25;

//Cansettoaconstorvar;maybeinitializedinaconstructor

readonlyfloatMIN_DIAMETER=4.93f;

VB.NET

Enumerations

C#

EnumAction

 Start 

 [Stop]   'Stop isareservedword

 Rewind

 Forward

EndEnum

Enum Status

 Flunk=50

 Pass=70

 Excel=90

EndEnum

DimaAsAction=Action.Stop

Ifa<>Action.StartThen_

  Console.WriteLine(a.ToString&"is"&a)   'Prints"Stopis1"

Console.WriteLine(Status.Pass)    'Prints70

Console.WriteLine(Status.Pass.ToString())    'PrintsPass

enumAction{Start,Stop,Rewind,Forward};

enumStatus{Flunk=50,Pass=70,Excel=90};

Actiona=Action.Stop;

if(a!

=Action.Start)

 Console.WriteLine(a+"is"+(int)a);    //Prints"Stopis1"

Console.WriteLine((int)Status.Pass);   //Prints70

Console.WriteLine(Status.Pass);   //PrintsPass

VB.NET

Operators

C#

Comparison

= < > <= >= <>

Arithmetic

+ - * /

Mod

\ (integerdivision)

^ (raisetoapower)

Assignment

= += -= *= /= \= ^= <<= >>= &=

Bitwise

And Or Xor Not << >>

Logical

AndAlso OrElse And Or Xor Not

Note:

AndAlsoandOrElseperformshort-circuitlogicalevaluations

StringConcatenation

&

Comparison

== < > <= >= !

=

Arithmetic

+ - * /

% (mod)

/ (integerdivisionifbothoperandsareints)

Math.Pow(x,y)

Assignment

= += -= *= /= %= &= |= ^= <<= >>= ++ --

Bitwise

& | ^ ~ << >>

Logical

&& || & | ^ !

Note:

&&and || performshort-circuitlogicalevaluations

StringConcatenation

+

VB.NET

Choices

C#

greeting=IIf(age<20,"What'sup?

","Hello")

'Onelinedoesn'trequire"EndIf"

Ifage<20Thengreeting="What'sup?

"

Ifage<20Thengreeting="What'sup?

"Elsegreeting="Hello"

'Use:

toputtwocommandsonsameline

Ifx<>100Andy<5Thenx*=5:

y*=2  

'Preferred

Ifx<>100Andy<5Then

 x*=5

 y*=2

EndIf

'Tobreakupanylongsinglelineuse_

IfwhenYouHaveAReally

 itNeedsToBeBrokenInto2 >Lines Then_

 UseTheUnderscore(charToBreakItUp)

'Ifx>5Then

 x*=y

ElseIf x=5Then

 x+=y

ElseIfx<10Then

 x-=y

Else

 x/=y

EndIf

SelectCasecolor  'Mustbeaprimitivedatatype

 Case"pink","red"

   r+=1

 Case"blue"

   b+=1

 Case"green"

   g+=1

 CaseElse

   other+=1

EndSelect

greeting=age<20?

"What'sup?

":

"Hello";

if(age<20)

 greeting="What'sup?

";

else

 greeting="Hello";

//Multiplestatementsmustbeenclosedin{}

if(x!

=100&&y<5){   

 x*=5;

 y*=2;

}

Noneedfor_or:

since;isusedtoterminateeachstatement.

if(x>5)

 x*=y;

elseif(x==5)

 x+=y;

elseif(x<10)

 x-=y;

else

 x/=y;

//Everycasemustendwithbreakorgotocase

switch(color) {                         //Mustbeintegerorstring

 case"pink":

 case"red":

   r++;   break;

 case"blue":

  b++;  break;

 case"green":

g++;  break;

 default:

   other++;  break;     //breaknecessaryondefault

}

VB.NET

Loops

C#

Pre-testLoops:

Whilec<10

 c+=1

EndWhile

DoUntilc=10 

 c +=1

Loop

DoWhilec<10

 c+=1

Loop

Forc=2To10Step2

 Console.WriteLine(c)

Next

Post-testLoops:

Do 

 c+=1

LoopWhilec<10

Do 

 c+=1

LoopUntilc=10

' Arrayorcollectionlooping

DimnamesAsString()={"Fred","Sue","Barney"}

ForEachsAsString Innames

 Console.WriteLine(s)

Next

'Breakingoutofloops

DimiAsInteger=0

While(True)

 If(i=5)ThenExitWhile

 i+=1

EndWhile

'Continuetonextiteration

Fori=0To4

 Ifi<4ThenContinueFor

 Console.WriteLine(i) 'Onlyprints4

Next

Pre-testLoops:

 

//no"until"keyword

while(c<10)

 c++;

for(c=2;c<=10;c+=2)

 Console.WriteLine(c);

Post-testLoop:

do

 c++;

while(c<10);

//Arrayorcollectionlooping

string[]names={"Fred","Sue","Barney"};

foreach(stringsinnames)

 Console.WriteLine(s);

//Breakingoutofloops

inti=0;

while(true){

 if(i==5)

  break;

 i++;

}

//Continuetonextiteration

for(i=0;i<5;i++){

 if(i<4)

  continue;

 Console.WriteLine(i); //Onlyprints4

}

VB.NET

Arrays

C#

Dimnums()AsInteger={1,2,3} 

ForiAsInteger=0Tonums.Length-1

 Console.WriteLine(nums(i))

Next

'4istheindexofthelastelement,soitholds5elements

Dimnames(4)AsString

names(0)="David"

names(5)="Bobby" 'ThrowsSystem.IndexOutOfRangeException

'Resizethearray,keepingtheexistingvalues(Preserveisoptional)

ReDimPreservenames(6)

DimtwoD(rows-1,cols-1)AsSingle

twoD(2,0)=4.5

Dimjagged()()AsInteger={_

 NewInteger(4){},NewInteger

(1){},NewInteger

(2){}}

jagged(0)(4)=5

int[]nums={1,2,3};

for(inti=0;i

 Console.WriteLine(nums[i]);

//5isthesizeofthearray

string[]names=newstring[5];

names[0]="David";

names[5]="Bobby";  //ThrowsSystem.IndexOutOfRangeException

//C#can'tdynamicallyresizeanarray. Justcopyintonewarray.

string[]names2=newstring[7];

Array.Copy(names,names2,names.Length);  //ornames.CopyTo(names2,0); 

float[,]twoD=newfloat[rows,cols];

twoD[2,0]=4.5f; 

int[][]jagged=newint[3][]{

 newint[5],newint[2],newint[3]};

jagged[0][4]=5;

VB.NET

Functions

C#

'Passbyvalue(in,default),reference(in/out),and reference(out) 

SubTestFunc(ByValxAsInteger,ByRefyAsInteger,ByRefzAsInteger)

 x+=1

 y+=1

 z=5

EndSub

Dima=1,b=1,cAsInteger  'c settozerobydefault 

TestFunc(a,b,c)

Console.WriteLine("{0}{1}{2}",a,b,c)  '1 25

'Acceptvariablenumberofarguments

FunctionSum(ByValParamArraynumsAsInteger())AsInteger

 Sum=0 

 ForEachiAsIntegerInnums

   Sum+=i

 Next

EndFunction  'OruseReturnstatementlikeC#

DimtotalAsInteger=Sum(4,3,2,1)  'returns10

'Optionalparametersmustbe listedlast andmusthaveadefaultvalue

SubSayHello(ByValnameAsString,OptionalByValprefixAsString="")

  Console.WriteLine("Greetings,"&prefix&""&name)

EndSub

SayHello("Strangelove","Dr.")

SayHello("Madonna")

//Passbyvalue(in,default),reference(in/out),and reference(out)

voidTestFunc(intx,refinty,outintz){

 x++;  

 y++;

 z=5;

}

inta=1,b=1,c; //cdoesn'tneedinitializing

TestFunc(a,refb,outc);

Console.WriteLine("{0}{1}{2}",a,b,c); //125

//Acceptvariablenumb

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 高等教育 > 农学

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1