2011/12/01

Delphi:使用record讓Function傳回兩個以上的值

記錄一下使用record的基本方法





步驟1:在uses下加入type end
 type
 TFunc = record  //TFunc自取名字,用T開頭就行了
  a :String;   //回傳的變數,需要回傳幾組就設定幾組,可以是各種型態
  b :Integer;
 end;

在uses下有一個TForm1 = class(TForm),加入的TFunc位置相當重要,如果TFunc在TForm1之後,那麼步驟2建立的Function可能無法使用TForm1裡的元件,所以建議TFunc要在TForm1之前。

步驟2:建立Function
type
 TForm1 = class(TForm)
  Button1: TButton;
  function GetRec(): TFunc;//建立function,回傳值設定為TFunc
  procedure Button1Click(Sender: TObject);
 private
  { Private declarations }
 public
  { Public declarations }
 end;
var
 Form1: TForm1;
 ...(中略)...

function TForm1.GetRec(): TFunc;
begin
 Result.a := '回傳值';     //.a與.b是對應TFunc下的變數
 Result.b := 1234567;
end;


步驟3:使用Function
procedure TForm1.Button1Click(Sender: TObject);
var tmp :TFunc; //建立一個變數,型態為TFunc
begin
 tmp := GetRec(); //將GetRec的值傳入tmp變數
 showmessage( tmp.a + ':' + inttostr(tmp.b) );
end;


最後輸出結果:
 回傳值:1234567


註:使用record不需要釋放,把它視為和String、Integer這種東西就可以,就像var x:String後不用釋放x一樣。

整個範例檔:
unit Unit1;

interface

uses
 Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
 StdCtrls;
type
 TFunc = record
 a :String;
 b :Integer;
end;
type
 TForm1 = class(TForm)
  Button1: TButton;
  function GetRec(): TFunc;
  procedure Button1Click(Sender: TObject);
 private
  { Private declarations }
 public
  { Public declarations }
 end;

var
 Form1: TForm1;

implementation

{$R *.DFM}

function TForm1.GetRec(): TFunc;
begin
 Result.a := '回傳值';
 Result.b := 1234567;
end;

procedure TForm1.Button1Click(Sender: TObject);
var tmp :TFunc;
begin
 tmp := GetRec();
 showmessage(tmp.a+':'+inttostr(tmp.b));
end;

end.


1 則留言: