DELPHI与C#语法比较.docx
《DELPHI与C#语法比较.docx》由会员分享,可在线阅读,更多相关《DELPHI与C#语法比较.docx(17页珍藏版)》请在冰点文库上搜索。
DELPHI与C#语法比较
窗体顶端
窗体底端
您查询的关键词是:
delphi c# 。
如果打开速度慢,可以尝试快速版;如果想保存快照,可以添加到搜藏。
(XX和网页
帮助 | 留言交流 |
首页我的图书馆主题阅读精彩目录精品文苑Tags会员浏览好书推荐
DELPHI与C#语法比较(转载)
kenwang收录于2007-04-05阅读数:
公众公开
原文来源
DELPHIandC#Comparison
DELPHI7与C#语法比较
编制:
黄焕尧参考:
VB.netandC#Comparison日期:
2005-5-30.
Comments注释
DataTypes数据类
Constants常量
Enumerations枚举
Operators运算
Choices选择语句
Loops循环语句
Arrays数组
Functions函数
ExceptionHandling异常处理
Namespaces命名空间
Classes/Interfaces
Constructors/Destructors构造/释构
Objects对象
Structs结构
Properties属性
Delegates/Events
ConsoleI/O
FileI/O
DELPHI
C#
Comments注释
//Singlelineonly
{ Multiple
line}
(* Multiple
line*)
//Singleline
/*Multiple
line */
///XMLcommentsonsingleline
/**XMLcommentsonmultiplelines*/
DataTypes数据类型
ValueTypes简单类型
Boolean
Byte
Char (example:
"A"c)
Word,Integer,Int64
Real,Single,Double,Real48,Extended,Comp,Currency
Decimal
Tdate,TDateTime
ReferenceTypes
Object
String(ShortString,AnsiString,WideString)
Set,array,record,file,class,classreference,interface
pointer,procedural,variant
varx:
Integer;
WriteLine(x); // PrintsSystem.Int32
WriteLine('Ingeger’); //PrintsInteger
// Typeconversion
varnumDecimal:
Single=3.5;
varnumInt:
Integer;
numInt:
=Integer(numDecimal) //setto4(Banker'srounding)
thedecimal)
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_STUDENTS:
Integer=25;
constintMAX_STUDENTS=25;
Enumerations枚举
TypeTaction1=(Start,Stop,Rewind,Forward);
{$M+}
TypeStatus=(Flunk=50,Pass=70,Excel=90);
{$M-}
vara:
Taction1=Stop;
Ifa<>StartThenWriteLn(ord(a)); //Prints 1
WriteLine(Ord(Pass)); //Prints70
WriteLine(GetEnumName(TypeInfo(Status),Ord(Pass))); //PrintsPass
ShowEnum(Pass);//outputs70
GetEnumValue(GetEnumName(TypeInfo(Status),’Pass’));//70
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比较
= < > <= >= <>inas
Arithmetic算述述运算
+ - * /div
Mod
\ (integerdivision)
^ (raisetoapower)阶乘
Assignment赋值分配
:
= Inc() Dec() shl shr
Bitwise位运算
and xor or not shl shr
//Logical
and xor or not
//StringConcatenation
+
Comparison
== < > <= >= !
=
Arithmetic
+ - * /
% (mod)
/ (integerdivisionifbothoperandsareints)
Math.Pow(x,y)
Assignment
= += -= *= /= %= &= |= ^= <<= >>= ++ --
Bitwise
& | ^ ~ << >>
Logical
&& || !
Note:
&&and || performshort-circuitlogicalevaluations
StringConcatenation
+
Choices判断
greeting:
=IfThen(age<20,'What'sup?
’,'Hello’);
Iflanguage='DELPHI’Then
langType:
='hymnlan’;
//
Ifx<>100Then
begin
x:
=x*5;y:
=x*2;
end;
// ortobreakupanylongsinglecommanduse_
If (whenYouHaveAReally< longLine)
and(itNeedsToBeBrokenInto2 >Lines Then
UseTheUnderscore(charToBreakItUp);
'Ifx>5Then
x:
=x*y
ElseIf x=5Then
x:
=x+y
ElseIfx<10Then
x:
=x-y
Else
x:
=x/y;
Casecolor of //不能为字符串类型
pink,red:
r:
=r+1;
blue:
b:
=b+1;
green:
g:
=g+1;
Else
Inc(other);
End;
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<10do
Inc(c);
End
Forc=2To10do
WriteLn(IntToStr(c));
Forc=10DownTo2do
WriteLn(IntToStr(c));
repeat
Inc(c);
Untilc=10 ;
// Arrayorcollectionlooping
countnames:
array[]ofString=('Fred’,'Sue’,'Barney’)
Fori:
=low(name)toHigh(name)do
WriteLn(name[i]);
DELPHI8开始支持for…each…语法
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数组
varnums:
array[]ofInteger=(1,2,3)
Fori:
=0ToHigh(nums)do
WriteLn(IntToStr(nums[i]))
//4is theindexofthelastelement,soitholds5elements
varnames:
array[0..5]ofString;//用子界指定数组范围
names[0]="David"
names[5]="Bobby"
//Resizethearray,keepingtheexistingvalues
SetLength(names,6);
vartwoD:
array[rows-1,cols-1]ofSingle;
twoD[2,0]:
=4.5;
varjagged:
array[]ofInteger=((0,0,0,0),(0,0,0,0));
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)
procedureTestFunc(x:
Integer,vary:
Integer,varz:
Integer)
;
begin
x:
=x+1;
y:
=y+1;
z:
=5;
End;
counta=1;
varb:
integer=1;c:
Integer=0; //c settozerobydefault
TestFunc(a,b,c);
WriteLn(Format('%d%d%d’,[a,b,c]); //1 25
//Acceptvariablenumberofarguments
FunctionSum(nums:
array[]ofInteger):
Integer;
begin
Result:
=0;
Fori:
=Low(nums)tohigh(nums)do
Result:
=Result+I;
End
vartotal:
Integer;
total:
=Sum(4,3,2,1); //returns10
//Optionalparametersmustbe listedlast andmusthaveadefaultvalue
procedureSayHello(name:
String;prefix:
String='’);
begin
WriteLn('Greetings,'+prefix+''+name);
End;
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
varex:
TException;
ex:
=TException.Create('Somethingisreallywrong.’);
Try//DELPHI不支持异常捕捉与Finally同时使用
Try
y=0
x=10/y
except
ONEx:
Exception
Do
ify=0then'
WriteLn(ex.Message);
end;
Finally
Beep();
End;
Exceptionup=newException("Somethingisreallywrong.");
throwup; //haha
try{
y=0;
x=10/y;
}
catch(Exceptionex){ //Argumentisoptional,no"When"keyword
Console.WriteLine(ex.Message);
}
finally{
//MustuseunmanagedMessageBeepAPIfunctiontobeep
}
Namespaces命名空间
//delphi无命名空间,以单元与之对应
UnitHarding;
...
End.
usesHarding;
namespaceHarding.Compsci.Graphics{
...
}
//or
namespaceHarding{
namespaceCompsci{
namespaceGraphics{
...
}
}
}
usingHarding.Compsci.Graphics;
Classes/Interfaces类和接口
Accessibilitykeywords界定关键字
Public
Private
Protected
published
//Protected
TypeFootballGame=Class
Protected
Competition:
string;
...
End
//Interfacedefinition
TypeIalarmClock=Interface(IUnknown)
...
End//endInterface
//Extendinganinterface
TypeIalarmClock=Interface(IUnknown)
['{00000115-0000-0000-C000-000000000044}']
functionIclock:
Integer;
...
End//endInterface
//Interfaceimplementation
TypeWristWatch=Class(TObject,IAlarmClock,ITimer)
functionIclock:
Integer;
...
End
Accessibilitykeywords
public
private
internal
protected
protectedinternal
static
//Inheritance
class FootballGame:
Competition{
...
}
//Interfacedefinition
interfaceIAlarmClock{
...
}
//Extendinganinterface
interfaceIAlarmClock:
IClock{
...
}
//Interfaceimplementation
classWristWatch:
IAlarmClock,ITimer{
...
}
Constructors/Destructors构造/释构
TypeSuperHero=Class
Private
ApowerLevel:
Integer;