VB和C#.docx
- 文档编号:259419
- 上传时间:2023-04-28
- 格式:DOCX
- 页数:11
- 大小:21.48KB
VB和C#.docx
《VB和C#.docx》由会员分享,可在线阅读,更多相关《VB和C#.docx(11页珍藏版)》请在冰点文库上搜索。
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
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- VB C#