VB和C#.docx

上传人:b****1 文档编号:259419 上传时间:2023-04-28 格式:DOCX 页数:11 大小:21.48KB
下载 相关 举报
VB和C#.docx_第1页
第1页 / 共11页
VB和C#.docx_第2页
第2页 / 共11页
VB和C#.docx_第3页
第3页 / 共11页
VB和C#.docx_第4页
第4页 / 共11页
VB和C#.docx_第5页
第5页 / 共11页
VB和C#.docx_第6页
第6页 / 共11页
VB和C#.docx_第7页
第7页 / 共11页
VB和C#.docx_第8页
第8页 / 共11页
VB和C#.docx_第9页
第9页 / 共11页
VB和C#.docx_第10页
第10页 / 共11页
VB和C#.docx_第11页
第11页 / 共11页
亲,该文档总共11页,全部预览完了,如果喜欢就下载吧!
下载资源
资源描述

VB和C#.docx

《VB和C#.docx》由会员分享,可在线阅读,更多相关《VB和C#.docx(11页珍藏版)》请在冰点文库上搜索。

VB和C#.docx

VB和C#

VB.NET

C#

Comments

'Singlelineonly

Rem Singlelineonly

//Singleline

/*Multiple

   line */

///XMLcommentsonsingleline

/**XMLcommentsonmultiplelines*/

DataTypes

ValueTypes

Boolean

Byte

Char  (example:

"A"c)

Short,Integer,Long

Single,Double

Decimal

Date

ReferenceTypes

Object

String

DimxAsInteger

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

Console.WriteLine(TypeName(x)) 'PrintsInteger

' Typeconversion

DimnumDecimalAsSingle=3.5

DimnumIntAsInteger

numInt=CType(numDecimal,Integer)  'setto4(Banker'srounding)

numInt=CInt(numDecimal) 'sameresultasCType

numInt=Int(numDecimal)   'setto3(Intfunctiontruncatesthedecimal)

ValueTypes

bool

byte,sbyte

char  (example:

'A')

short,ushort,int,uint,long,ulong

float, double

decimal

DateTime  (notabuilt-inC# type)

ReferenceTypes

object

string

intx;

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

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

//Typeconversion

doublenumDecimal=3.5;

intnumInt=(int)numDecimal;  //setto 3 (truncatesdecimal)

Constants

Const MAX_STUDENTSAsInteger=25

constintMAX_STUDENTS=25;

Enumerations

EnumAction

 Start 

 [Stop]   'Stop isareservedword

 Rewind

 Forward

EndEnum

Enum Status

 Flunk=50

 Pass=70

 Excel=90

EndEnum

DimaAsAction=Action.Stop

Ifa<>Action.StartThenConsole.WriteLine(a)   'Prints 1

Console.WriteLine(Status.Pass)    'Prints70

DimsAsType=GetType(Status)

Console.WriteLine([Enum].GetName(s,Status.Pass))   '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(Status.Pass);   //PrintsPass

Operators

Comparison

= < > <= >= <>

Arithmetic

+ - * /

Mod

\ (integerdivision)

^ (raisetoapower)

Assignment

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

Bitwise

And  AndAlso Or  OrElse Not << >>

Logical

And AndAlso Or  OrElse  Not

Note:

AndAlsoandOrElseareforshort-circuitinglogicalevaluations

StringConcatenation

&

Comparison

== < > <= >= !

=

Arithmetic

+ - * /

% (mod)

/ (integerdivisionifbothoperandsareints)

Math.Pow(x,y)

Assignment

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

Bitwise

& | ^   ~ << >>

Logical

&& ||  !

Note:

&&and || performshort-circuitlogicalevaluations

StringConcatenation

+

Choices

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

","Hello")

'Onelinedoesn'trequire"EndIf",no"Else"

Iflanguage="VB.NET"ThenlangType="verbose"

'Use:

toputtwocommandsonsameline

Ifx<>100Thenx*=5:

y*=2  

' ortobreakupanylongsinglecommanduse_

If whenYouHaveAReally< longLineAnditNeedsToBeBrokenInto2 >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(x!

=100){   //Multiplestatementsmustbeenclosedin{}

 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;

switch(color) {                         //Mustbeintegerorstring

 case"pink":

 case"red":

   r++;   break;      //breakismandatory;nofall-through

 case"blue":

  b++;  break;

 case"green":

g++;  break;

 default:

   other++;  break;     //breaknecessaryondefault

}

Loops

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

Pre-testLoops:

 

//no"until"keyword

while(i<10)

 i++;

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

 Console.WriteLine(i);

Post-testLoop:

do

 i++;

while(i<10);

//Arrayorcollectionlooping

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

foreach(stringsinnames)

 Console.WriteLine(s);

Arrays

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

ForiAsInteger=0Tonums.Length-1

 Console.WriteLine(nums(i))

Next

'4is theindexofthelastelement,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#doesn'tcan'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;

Functions

'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

//Acceptvariablenumberofarguments

intSum(paramsint[]nums){

 intsum=0;

 foreach(intiinnums)

   sum+=i;

 returnsum;

}

inttotal=Sum(4,3,2,1);  //returns10

/*C#doesn't supportoptionalarguments/parameters. Justcreatetwodifferentversionsofthesamefunction.*/ 

voidSayHello(stringname,stringprefix){

 Console.WriteLine("Greetings,"+prefix+""+name);

voidSayHello(stringname){

 SayHello(name,"");

}

ExceptionHandling

'Deprecatedunstructurederrorhandling

OnErrorGoToMyErrorHandler

...

MyErrorHandler:

Console.WriteLine(Err.Description)

DimexAsNewException("Somethingisreallywrong.")

Throw ex 

Try 

 y=0

 x=10/y

CatchexAsException Wheny=0'ArgumentandWhenisoptional

 Console.WriteLine(ex.Message)

Finally

 Beep()

EndTry

Exceptionup=newException("Somethingisreallywrong.");

throwup; //haha

try{ 

 y=0;

 x=10/y;

}

catch(Exceptionex){  //Argumentisoptional,no"When"keyword 

 Console.WriteLine(ex.Message);

}

finally{

 //MustuseunmanagedMessageBeepAPIfunctiontobeep

}

Namespaces

NamespaceHarding.Compsci.Graphics 

 ...

EndNamespace

'or

NamespaceHarding

 NamespaceCompsci

   NamespaceGraphics 

     ...

   EndNamespace

 EndNamespace

EndNamespace

ImportHarding.Compsci.Graphics

namespaceHarding.Compsci.Graphics{

 ...

}

//or

namespaceHarding{

 namespaceCompsci{

   namespaceGraphics{

     ...

   }

 }

}

usingHarding.Compsci.Graphics;

Classes/Interfaces

Accessibilitykeywords

Public

Private

Friend                   

Protected

ProtectedFriend

Shared

'Inheritance

Class FootballGame

 Inherits Competition

 ...

EndClass 

'Interfacedefinition

InterfaceIAlarmClock 

 ...

EndInterface

//Extendinganinterface 

InterfaceIAlarmClock

 InheritsIClock

 ...

EndInterface

//Interfaceimplementation

ClassWristWatch 

 ImplementsIAlarmClock,ITimer 

  ...

EndClass 

Accessibilitykeywords

public

private

internal

protected

protectedinternal

static

//Inheritance

class FootballGame:

Competition{

 ...

}

//Interfacedefinition

interfaceIAlarmClock{

 ...

}

//Extendinganinterface 

interfaceIAlarmClock:

IClock{

 ...

}

//Interfaceimplementation

classWristWatch:

IAlarmClock,ITimer{

  ...

}

Constructors/Destructors

ClassSuperHero

 Private _powerLevelAsInteger

 PublicSubNew()

   _powerLevel=0

 EndSub

 PublicSubNew(ByValpowerLevelAsInteger)

   Me._powerLevel=powerLevel

 EndSub

 ProtectedOverridesSubFinalize() 

   'Desctructorcodetofreeunmanagedresources

   MyBase.Finalize()

 EndSub

EndClass

classSuperHero{

 privateint_powerLevel;

 publicSuperHero(){

     _powerLevel=0;

 }

 p

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

当前位置:首页 > 自然科学 > 物理

copyright@ 2008-2023 冰点文库 网站版权所有

经营许可证编号:鄂ICP备19020893号-2