Delphiの基本構文
変数の宣言(var)
//string型変数stの宣言(VBのDimです) var st:string;
変数の基本型
var st:string; //文字列型上記以外にも沢山の型がある。上記等は基本型なのでクラスではない為、使用しなくなってもメモリ破棄など不要。
c:char; //文字型
i:inreger; //整数型(VBではLong) s:single; //小数型 d:double; //倍精度小数型整数型
変数への値の代入
Delphiでは変数への代入に := を使う。//以下は変数iに0を代入している i := 0; //以下は変数stに文字列「ほげほげ」を代入している st := 'ほげほげ'; //以下は変数dに1.25を代入している d := 1.25;
条件文
if a=b then begin //a=bの時の処理; end; if a=b then begin //a=bの時の処理; end else begin //a=bでは無い時の処理 end; if a=b then begin //a=bの時の処理; end else if b=c then begin //b=cの時の処理; end else begin //a=bでも無くb=cでも無い時の処理; end; if (a=b) and (b=c) then begin //a=bかつb=cの時の処理; end; if (a=b) or (b=c) then begin //a=b又はb=cの時の処理; end; //begin~endを省略した使い方 if a=b then a=20; if a=b then a=20 else b=20;
ループ(for)
以下は変数iに1~10の値を代入してc:=c+iを10回ループしているfor i=1 to 10 do begin c:=c+i; end;以下は変数iに10~1の値を代入してc:=c+iを10回ループしている
for i=10 downto 1 do begin c:=c+i; end;
ループ(while)
条件が真(以下ではiが10未満)の間ループする。が、iが8になったら抜けるi := 0; while i<10 do begin i := i + 1; if i = 8 then break; end;
構造体(record)
Delphiは暗黙の了解で構造体やクラス型の名前の先頭は大文字Tから始まるtype TMyRecord = record name:string; age:integer; end; procedure TForm1.Button1Click(Sender: TObject); var mr:TMyRecord; begin mr.name:='ほげ'; mr.age:=24; end;
クラス(class)
いきなりですが、それなりのサンプルを提示unit Unit2; interface type TMyClass=class(TObject) private fname:string; //private等のフィールド変数にはfを付ける暗黙の了解がある fage:integer; function getage():integer; procedure setage(value:integer); public Constructor Create(); property name:string read fname write fname; //fnameをプロパティnameで公開する。 property age:integer read getage write setage; //fageをageプロパティとして関数getageとsetageを介して公開する。 end; implementation constructor TMyClass.Create; begin //コンストラクター。このクラスが作成されるときに実行される fname:=''; fage:=0; end; function TMyClass.getage: integer; begin result:=fage; end; procedure TMyClass.setage(value: integer); begin if value>=0 then fage:=value; end; end.上記クラスを使うサンプル
procedure TForm1.Button1Click(Sender: TObject); var mc:TMyClass; begin mc:=TMyClass.Create; //インスタンスの作成 mc.name := 'ほげ'; mc.age := 24; mc.Free; //破棄する(メモリ解放される) end;
クラス2(class)
コンストラクターとデストラクターunit Unit3; interface uses System.Classes; type TMyClass2=class(TObject) private fstl:TStringList; public procedure addList(value:string); function getValue(index:integer):string; Constructor Create(); Destructor Destroy; end; implementation { TMyClass2 } procedure TMyClass2.addList(value: string); begin fstl.Add(value); end; constructor TMyClass2.Create; begin fstl:=TStringList.Create; end; destructor TMyClass2.Destroy; begin fstl.Free; end; function TMyClass2.getValue(index: integer): string; begin result:=''; if index<fstl.Count then begin result:=fstl[index]; end; end; end.上記クラスを使うサンプル
procedure TForm1.Button1Click(Sender: TObject); var mc2:TMyClass2; begin mc2:=TMyClass2.Create; mc2.addList('ほげ'); mc2.addList('ほげほげ'); showmessage(mc2.getValue(0)); mc2.Free; end;