我只是想掌握单独单元的窍门,以使我的代码更加封装。我正在尝试整理我的方法的公共/私有声明,以便我可以从使用的其他单元调用它们 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
有帮助吗?

解决方案

单元结构看起来有点像从对象的公共/私人部分,你可以说这是他们的先行者。但语法不同。

您只必须声明方法头在接口部分,如下所示:

interface
  procedure hellofromotherunit();

implementation
  procedure hellofromotherunit(); begin .. end;

只允许每个部分中的一个。

其他提示

私人及公共仅适用于类。

您想要做的就是把hellofromotherunit的声明的副本进入界面部分是什么。不要把stickletter的声明的副本在那里,但是。

这出现在接口部是任何有效地公开。凡是只是倒在实现是私有的。

此外,

每个单元都有两个不同的部分。接口和实现。

接口部分包含所有公共定义(类型、过程标题、常量)。实施部分包含所有实施细节。

当您使用一个单位时,(使用uses子句)您可以访问该单位的公共定义。此访问不是递归的,因此如果单元 A 接口使用单元 B,并且单​​元 C 使用单元 A,则您无法访问单元 B,除非显式使用它。

实现部分可以访问接口以及两个 use 子句(接口和实现)中使用的单元。

首先编译所使用单元的接口,然后再继续编译其余单元。这样做的优点是您可以在实现中具有循环依赖关系:

unit A;
interface
uses B;

unit B;
interface
implementation
uses A;

哪个编译:

  • 尝试接口A,失败需要B
  • 尝试一下B接口,ok!
  • 尝试一下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.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top