知识大全 如何在程序中使用自己的库单元

Posted

篇首语:不怕学问浅,就怕志气短。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 如何在程序中使用自己的库单元相关的知识,希望对你有一定的参考价值。

  用过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);BeginTmessage:=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);BeginTmessage:=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 Unit ;

interface

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

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

var   Form : TForm ;   Tclass:CTestclass; file://你要增加的类的引用声明

implementation

$R * dfm

procedure TForm FormCreate(Sender: TObject);begin     Tclass Create;     Tclass SetText( 这是一个类的测试 );     showmessage(Tclass GetText); file://此处是对你自己写的类的一个测试end;

end

cha138/Article/program/Delphi/201311/25041

相关参考