如何在Delphi中使用单位文件
我只是想弄清楚不同单元的诀窍,使代码更加封装。 我正在尝试整理我的方法的公共/私有声明,以便可以从使用如何在Delphi中使用单位文件,delphi,private,pascal,public,delphi-units,Delphi,Private,Pascal,Public,Delphi Units,我只是想弄清楚不同单元的诀窍,使代码更加封装。 我正在尝试整理我的方法的公共/私有声明,以便可以从使用testunit的其他单元调用它们。在本例中,我想将hellofromotherunit设置为公共,但将stickletters设置为私有 unit testunit; interface uses Windows, Messages, Dialogs; implementation function stickletters(a,b:string):string;
testunit
的其他单元调用它们。在本例中,我想将hellofromotherunit设置为公共,但将stickletters设置为私有
unit testunit;
interface
uses
Windows, Messages, Dialogs;
implementation
function stickletters(a,b:string):string;
begin
result:=a+b;
end;
procedure hellofromotherunit();
begin
showmessage(stickletters('h','i'));
end;
end.
我似乎无法从其他单位复制私人/公共结构,如:
Type
private
function stickletters(a,b:inter):integer;
public
procedure hellofromotherunit();
end
私有和公共仅适用于类 您要做的是将hellofromotherunit声明的副本放入interface部分。但是,不要把斯蒂克勒声明的副本放在上面
界面部分中出现的任何内容实际上都是公共的。任何只在实现中出现的部分都是私有的。单元结构看起来有点像对象中的公共/私有部分,可以说它是它们的前身。但是语法是不同的 只需在接口部分声明方法头,如中所示:
interface
procedure hellofromotherunit();
implementation
procedure hellofromotherunit(); begin .. end;
每个部分只允许一个。此外
每个单元有两个不同的部分。接口和实现
接口部分包含所有公共定义(类型、过程标题、常量)。“实施”部分包含所有实施详细信息
使用单元时,(使用uses子句)可以访问该单元的公共定义。这种访问不是递归的,所以如果单元A接口使用单元B,而单元C使用单元A,那么除非显式使用单元B,否则无法访问单元B
实现部分可以访问接口,访问两个use子句(接口和实现)中使用的单元
在继续编译其余单元之前,先编译使用单元的接口。这样做的好处是,您可以从实现中获得循环依赖关系:
unit A;
interface
uses B;
unit B;
interface
implementation
uses A;
其中汇编:
- 尝试接口A,失败需要B
- 试试界面B,好的李>
- 试试界面A,好的李>
- 试试实现A,好的李>
- 试试实现B,好的李>
unit A;
interface
const foo = 1;
unit B;
interface
const foo = 2;
unit C;
interface
uses A, B;
const
f1 = foo;
f2 = A.foo;
f3 = B.foo;
如果在多个已使用单位中定义了标识符,则采用“使用”列表中可能的最后一个单位。所以f1=2。但您可以使用单元(名称空间)名称作为前缀来解决此问题
随着.net的引入,允许使用多部分名称空间,这带来了其他一些不错的问题:
unit foo;
interface
type
rec1 = record
baz : Boolean;
end;
var
bar : rec1;
unit foo.bar;
interface
var
baz : Integer;
uses
foo, foo.bar;
begin
foo.bar.baz := true;
foo.bar.baz := 1;
end.
// 1. Which these lines gives an error and why?
// 2. Does the result change if you write uses foo.bar, foo?
在这种情况下,您会遇到冲突。但这可以通过赋予名称空间名称更高的优先级来解决。因此,第一行失败。只是不在接口部分声明方法,它将保持私有
unit Unit2;
interface
function MyPublicFunction():Boolean;
implementation
function MyPrivateFunction():Boolean;
begin
// blah blah
end;
function MyPublicFunction():Boolean;
begin
// blah blah
end;
end.