收藏 分享(赏)

DELPHI与C#语法比较.doc

上传人:11xg27ws 文档编号:7806407 上传时间:2019-05-26 格式:DOC 页数:13 大小:117.50KB
下载 相关 举报
DELPHI与C#语法比较.doc_第1页
第1页 / 共13页
DELPHI与C#语法比较.doc_第2页
第2页 / 共13页
DELPHI与C#语法比较.doc_第3页
第3页 / 共13页
DELPHI与C#语法比较.doc_第4页
第4页 / 共13页
DELPHI与C#语法比较.doc_第5页
第5页 / 共13页
点击查看更多>>
资源描述

1、DELPHI 与 C#语法比较(转载)kenwang 收录于 2007-04-05 阅读数: 公众公开 原文来源 DELPHI and C# ComparisonDELPHI7 与 C#语法比较编制:黄焕尧 参考:VB.net and C# Comparison 日期:2005-5-30. Comments 注释Data Types 数据类 Constants 常量Enumerations 枚举Operators 运算Choices 选择语句Loops 循环语句Arrays 数组Functions 函数Exception Handling 异常处理Namespaces 命名空间Classes

2、/ Interfaces Constructors / Destructors 构造/释构Objects 对象Structs 结构Properties 属性Delegates / Events Console I/O File I/O DELPHI C#Comments 注释/ Single line only Multiple line ( * Multiple line *)/ Single line/* Multipleline */ XML comments on single line/* XML comments on multiple lines */Data Types 数据类

3、型Value Types 简单类型BooleanByteChar (example: “A“c)Word, Integer, Int64Real ,Single, Double,Real48,Extended,Comp,CurrencyDecimalTdate,TDateTimeReference TypesObjectString(ShortString,AnsiString,WideString)Value Typesboolbyte, sbytechar (example: A)short, ushort, int, uint, long, ulongfloat, doubledecim

4、alDateTime (not a built-in C# type)Reference Typesobjectstringint x;Set, array, record, file,class,class reference,interfacepointer, procedural, variantvar x:Integer;WriteLine(x); / Prints System.Int32 WriteLine(Ingeger); / Prints Integer/ Type conversionvar numDecimal:Single = 3.5 ;var numInt:Integ

5、er;numInt :=Integer(numDecimal) / set to 4 (Bankers rounding)the decimal)Console.WriteLine(x.GetType(); / Prints System.Int32Console.WriteLine(typeof(int); / Prints System.Int32 / Type conversion double numDecimal = 3.5; int numInt = (int) numDecimal; / set to 3 (truncates decimal)Constants 常量Const

6、MAX_STUDENTS:Integer = 25; const int MAX_STUDENTS = 25;Enumerations 枚举Type Taction1=(Start, Stop, Rewind, Forward);$M+Type Status=(Flunk = 50, Pass = 70, Excel = 90);$M-var a:Taction1 = Stop; If a in asArithmetic 算述述运算+ - * / divMod (integer division) (raise to a power) 阶乘Assignment 赋值分配:= Inc() Dec

7、() shl shr Bitwise 位运算and xor or not shl shr/Logicaland xor or not/String Concatenation+Comparison= = !=Arithmetic+ - * /% (mod)/ (integer division if both operands are ints)Math.Pow(x, y)Assignment= += -= *= /= %= y :=x* 2; end;/ or to break up any long single command use _If (whenYouHaveAReally Li

8、nes Then greeting = age 5 Then x :=x* y Else If x = 5 Then x :=x+ y Else If x 5) x *= y; else if (x = 5) x += y; else if (x 10) x -= y; else x /= y;switch (color) / Must be integer or stringcase “pink“:case “red“: r+; break; / break is mandatory; no fall-throughcase “blue“: b+; break;case “green“: g

9、+; break;default: other+; break; / break necessary on default Loops 循环Pre-test Loops: While c 10 doInc(c) ;EndFor c = 2 To 10 do WriteLn(IntToStr(c); For c = 10 DownTo 2 doWriteLn(IntToStr(c); repeat Inc(c); Until c = 10 ;/ Array or collection loopingcount names:array of String = (Fred, Sue, Barney)

10、 Pre-test Loops: / no “until“ keywordwhile (i 10) i+;for (i = 2; i = 10; i += 2) Console.WriteLine(i);Post-test Loop:do i+; while (i 10);For i:=low(name) to High(name) do WriteLn(namei); DELPHI8 开始支持 for each 语法/ Array or collection loopingstring names = “Fred“, “Sue“, “Barney“;foreach (string s in

11、names)Console.WriteLine(s);Arrays 数组var nums:array of Integer = (1, 2, 3) For i := 0 To High(nums) do WriteLn(IntToStr(numsi) / 4 is the index of the last element, so it holds 5 elementsvar names:array05 of String; /用子界指定数组范围names0 = “David“names5 = “Bobby“ / Resize the array, keeping the existing v

12、alues SetLength(names,6);var twoD:arrayrows-1, cols-1 of Single; twoD2, 0 := 4.5;var jagged:array of Integer =(0,0,0,0),(0,0,0,0); jagged0,4 := 5; int nums = 1, 2, 3;for (int i = 0; i nums.Length; i+)Console.WriteLine(numsi);/ 5 is the size of the arraystring names = new string5;names0 = “David“;nam

13、es5 = “Bobby“; / Throws System.IndexOutOfRangeException / C# doesnt cant dynamically resize an array. Just copy into new array.string names2 = new string7; Array.Copy(names, names2, names.Length); / or names.CopyTo(names2, 0); float, twoD = new floatrows, cols;twoD2,0 = 4.5f; int jagged = new int3 n

14、ew int5, new int2, new int3 ;jagged04 = 5; Functions 函数 Pass by value(传值参数) (in, default), 传递引用参数 reference (in/out), and reference (out) procedure TestFunc( x:Integer, var y:Integer, var z:Integer);beginx :=x+1;y :=y+1; z := 5; End; count a = 1; var b:integer=1; c :Integer=0; / c set to zero by def

15、ault TestFunc(a, b, c); WriteLn(Format(%d %d %d,a, b, c); / 1 2 5/ Accept variable number of arguments Function Sum(nums:array of Integer):Integer;begin Result := 0; For i:=Low(nums) to high(nums) do Result := Result + I; End var total :Integer;total := Sum(4, 3, 2, 1); / returns 10/ Optional parame

16、ters must be listed last and must have a default value procedure SayHello( name:String;prefix:String = );beginWriteLn(Greetings, + prefix + + name); End;/ Pass by value (in, default), reference (in/out), and reference (out)void TestFunc(int x, ref int y, out int z) x+; y+;z = 5; int a = 1, b = 1, c;

17、 / c doesnt need initializingTestFunc(a, ref b, out c);Console.WriteLine(“0 1 2“, a, b, c); / 1 2 5/ Accept variable number of argumentsint Sum(params int nums) int sum = 0;foreach (int i in nums)sum += i;return sum;int total = Sum(4, 3, 2, 1); / returns 10/* C# doesnt support optional arguments/par

18、ameters. Just create two different versions of the same function. */ void SayHello(string name, string prefix) Console.WriteLine(“Greetings, “ + prefix + “ “ + name); void SayHello(string name) SayHello(name, “); SayHello(Strangelove, Dr.);SayHello(Madonna);Exception Handling 异常处理 Deprecated unstruc

19、tured error handlingvar ex :TException;ex:=TException.Create(Something is really wrong.); Try /DELPHI 不支持异常捕捉与Finally 同时使用Try y = 0x = 10 / yexcept ON Ex:Exception Doif y = 0 then WriteLn(ex.Message) ;end;Finally Beep(); End;Exception up = new Exception(“Something is really wrong.“); throw up; / ha

20、ha try y = 0; x = 10 / y; catch (Exception ex) / Argument is optional, no “When“ keyword Console.WriteLine(ex.Message); finally / Must use unmanaged MessageBeep API function to beep Namespaces 命名空间/delphi 无命名空间,以单元与之对应Unit Harding; .End.uses Harding; namespace Harding.Compsci.Graphics . / or namespa

21、ce Harding namespace Compsci namespace Graphics . using Harding.Compsci.Graphics; Classes / Interfaces 类和接口Accessibility keywords 界定关键字PublicPrivateProtectedpublished/ ProtectedType FootballGame= Class Protected Competition:string;.End / Interface definitionType IalarmClock= Interface (IUnknown) .En

22、d / end Interface/ Extending an interface Type IalarmClock= Interface (IUnknown)00000115-0000-0000-C000-000000000044function Iclock:Integer;.End /end Interface/ Interface implementationType WristWatch=Class(TObject, IAlarmClock ,ITimer) function Iclock:Integer;Accessibility keywords publicprivateint

23、ernalprotectedprotected internalstatic/ Inheritanceclass FootballGame : Competition . / Interface definitioninterface IAlarmClock . / Extending an interface interface IAlarmClock : IClock . / Interface implementationclass WristWatch : IAlarmClock, ITimer . .End Constructors / Destructors 构造/释构Type S

24、uperHero=ClassPrivate ApowerLevel:Integer; Public constructor Create;override; constructor New(powerLevel:Integer); virtual;destructor Destroy; override;end; /end Class InterfaceImplementationprocedure Create();beginApowerLevel := 0;end;procedure New(powerLevel:Integer);beginself.ApowerLevel := powe

25、rLevel;end;procedure Destroy;begininherited Destroy;endEnd. class SuperHero private int _powerLevel;public SuperHero() _powerLevel = 0;public SuperHero(int powerLevel) this._powerLevel= powerLevel; SuperHero() / Destructor code to free unmanaged resources./ Implicitly creates a Finalize methodObject

26、s 对象var hero:SuperHero;hero := SuperHero.Create; SuperHero hero = new SuperHero(); With hero Name := “SpamMan“; PowerLevel := 3; End /end With hero.Defend(Laura Jones); hero.Rest(); / Calling Shared method/ orSuperHero.Rest(); var hero2:SuperHero;hero2:= hero; / Both refer to same object hero2.Name

27、:= WormWoman; WriteLn(hero.Name) / Prints WormWomanhero.Free;hero = nil; / Free the object if hero= nil then hero := SuperHero.Create;var obj:Object;obj:= SuperHero.Create; if obj is SuperHero then WriteLn(Is a SuperHero object.);/ No “With“ constructhero.Name = “SpamMan“; hero.PowerLevel = 3; hero.

28、Defend(“Laura Jones“);SuperHero.Rest(); / Calling static methodSuperHero hero2 = hero; / Both refer to same object hero2.Name = “WormWoman“; Console.WriteLine(hero.Name); / Prints WormWoman hero = null ; / Free the object if (hero = null)hero = new SuperHero();Object obj = new SuperHero(); if (obj i

29、s SuperHero) Console.WriteLine(“Is a SuperHero object.“);Structs 记录/结构Type StudentRecord = packed Recordname:String;gpa:Single; End /end StructureVar stu:StudentRecord; stu.name:=Bob;stu:=3.5; var stu2:StudentRecord;stu2 := stu; struct StudentRecord public string name;public float gpa;public Student

30、Record(string name, float gpa) this.name = name;this.gpa = gpa;StudentRecord stu = new stu2.name := Sue; WriteLn(stu.name) / Prints Bob WriteLn(stu2.name) / Prints SueStudentRecord(“Bob“, 3.5f);StudentRecord stu2 = stu; stu2.name = “Sue“;Console.WriteLine(stu.name); / Prints BobConsole.WriteLine(stu

31、2.name); / Prints SueProperties 属性Private Asize:Integer;PublishedProperty Size:Integer read GetSize write SetSize;End;ImplementationFunction GetSize:Integer;beginResult:=Asize;end;procedure SetSize(Value:Integer);beginif Value0 thenAsize := 0elseAsuze := Value;end;foo.Size := foo.Size + 1;private in

32、t _size;public int Size get return _size; set if (value 0) _size = 0; else _size = value; foo.Size+; Delegates / Events 事件Type delegate void MsgArrivedEventHandler=prcedure(message:string) of object;MsgArrivedEvent:MsgArrivedEventHandler;TypeMyButton =Class(Tbutton)private FClick:MsgArrivedEventHand

33、ler;publicprocedure Click;property onClick:MsgArrivedEventHandler read Fclick write Fclick;end;ImplementationProcedure MyButton.Click;beginMessageBox (self.handle, Button was clicked, Info, MessageBoxButtonsOK, MessageBoxIconInformation);end;MsgArrivedEventHandler(string message); event MsgArrivedEv

34、entHandler MsgArrivedEvent;/ Delegates must be used with events in C#MsgArrivedEvent += new MsgArrivedEventHandler(My_MsgArrivedEventCallback);MsgArrivedEvent(“Test message“); / Throws exception if obj is nullMsgArrivedEvent -= new MsgArrivedEventHandler(My_MsgArrivedEventCallback);using System.Wind

35、ows.Forms;Button MyButton = new Button(); MyButton.Click += new System.EventHandler(MyButton_Click);private void MyButton_Click(object sender, System.EventArgs e) MessageBox.Show(this, “Button was clicked“, “Info“, MessageBoxButtons.OK, MessageBoxIcon.Information); Console I/ODELPHI 无控制台对象若为控制台程序则Write(count Text);Escape sequencesn, rt“WriteLn(count Text);Read(var Text);ReadLn(var Text);span lang=EN-US style=“FONT-SIZE: 12pt; FONT-FAMILY: SimSun; mso-font-kernin

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

当前位置:首页 > 企业管理 > 管理学资料

本站链接:文库   一言   我酷   合作


客服QQ:2549714901微博号:道客多多官方知乎号:道客多多

经营许可证编号: 粤ICP备2021046453号世界地图

道客多多©版权所有2020-2025营业执照举报