如何在程序中使用自己的库单元

来源:互联网 发布:直播美颜软件 编辑:程序博客网 时间:2024/04/28 11:51

用过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.

好了,在你的计算机中输入完上面的代码后,运行试一试吧。这里只是对库单元的引用举了一个简单例子,关于详细写法请参看相关书籍中对库单元及类编程的讲述。