如何在程式中使用自己的庫單元

來源:互聯網
上載者:User

用過VB的人都知道,可以在工程中增加類模快來存放共用方法,而在delphi中如何也能與VB一樣存放自己的類呢?通過下面的講解,我想你一定會有所收穫的。
一,在工程中增加一個庫單元
單擊菜單的順序為 File -> New -> Unit 這樣就為你的工程增加了一個庫單元。新增加的庫單元內容如:

 unit global;//庫單元的名字

 interface
           file://<---這裡加入選擇性庫單元列表
 implementation
 
 end.

二,在庫單元中增加自己的類
在Object Pascal中,用關鍵字Class來聲明類。使用如下文法:

 Type
     CTestclass = class  file://定義一個類,命名規律自己看一看delphi相關的命名規律
 end;

當然,這段代碼,沒有什麼實際用途,只是僅僅聲明了一個空類,而類在沒有任何的資料和操作,在下面我們可以向類中添加資料和方法。

 Type
     CTestclass = class
     Tmessage:String;
     Procedure SetText(text:String);
     Function GetText:String;
 end;

類的函數成員和過程成員成為類的方法。他們的說明和定義方法與普通的函數和過程相似,唯一的區別是要在函數名和過程名前面加類名和句點。
 Procdeure CTestclass.SetText(text:String);
 Begin
 Tmessage:=text;
 end;

 Function CTestclass.GetText:String;
 Begin
     GetText:=Tmessage;
 end;

這樣一個簡單的類就編寫完成了,你可以按下面所講的步驟進行調用。
將上面的代碼整理一下,這個庫單元的完整代碼如下:

 unit global;//庫單元的名字

 interface file://介面部分
 uses         
     windows;//需要引用的其它庫單元列表
 Type file://介面類型定義
     CTestclass = class
     Tmessage:String;
     Procedure SetText(text:String);
     Function GetText:String;
 end;

 implementation

 Procdeure CTestclass.SetText(text:String);
 Begin
 Tmessage:=text;
 end;

 Function CTestclass.GetText:String;
 Begin
     GetText:=Tmessage;
 end;

 end.

三,調用自訂庫單元檔案(或其它庫單元)中的方法
在你需要引用的檔案uses處,添加你自己的庫單元的名稱

 uses
   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
   Dialogs, global; file://注意這裡的global是你自己寫的庫單元的名稱

一旦在uses部分引用了你的庫單元,就可以按如下進行調用:
 Var
     Tclass:CTestclass;
     這樣一來就可以如當前檔案中的表單類一樣調用了。完整代碼如下:

 unit Unit1;

 interface

 uses
   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
   Dialogs, global;

 type
   TForm1 = class(TForm)
   private
     { Private declarations }
   public
     { Public declarations }
   end;

 var
   Form1: TForm1;
   Tclass:CTestclass; file://你要增加的類的引用聲明

 implementation

 {$R *.dfm}

 procedure TForm1.FormCreate(Sender: TObject);
 begin
     Tclass.Create;
     Tclass.SetText('這是一個類的測試');
     showmessage(Tclass.GetText); file://此處是對你自己寫的類的一個測試
 end;

 end.

好了,在你的電腦中輸入完上面的代碼後,運行試一試吧。這裡只是對庫單元的引用舉了一個簡單例子,關於詳細寫法請參看相關書籍中對庫單元及類編程的講述。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.