接口与类的区别

来源:互联网 发布:linux echo b重启 编辑:程序博客网 时间:2024/06/11 17:19

郁闷,一提交全没了提交一篇‘靠’,居然就成功了,火大阿
重新翻译了只好,当作温习了

来自Delphi Help,关键字Interface types: overview

接口和类一样,只能在程序或单元的最外层被声明(也就是interface section,也就是全局可见的),不能在过程或函数中声明。接口类型的声明格式如下:
type interfaceName = interface (ancestorInterface)  //关键字interface
   ['{GUID}']   //全局唯一标识符
 memberList    //成员列表
 end;
其中(ancestorInterface) 和['{GUID}'] 是可选的,接口声明和类相似,但是有如下的约束:
1,memberList只能包含方法和属性。字段在接口中是不允许的。
2,因为接口没有字段,属性的read和write指定的必须是方法。
3,所有接口的成员都是公开的(public)。可见性指定(private,protected等)和存储指定(如stored, default, nodefault)都不允许。(但是一个数组属性可以带关键字default,请看末尾的说明)
4,接口没有构造器和析构器。它不能被实例化,除了通过类来实现它的方法。
5,方法不能被声明成virtual,dynamic,abstract或者override。因为接口不实现它自己的方法,这些指定是没有意义的。
请看一个接口声明的例子:
type
  IMalloc = interface(IInterface)
    ['{00000002-0000-0000-C000-000000000046}']
    function Alloc(Size: Integer): Pointer; stdcall;
    function Realloc(P: Pointer; Size: Integer): Pointer; stdcall;
    procedure Free(P: Pointer); stdcall;
    function GetSize(P: Pointer): Integer; stdcall;
    function DidAlloc(P: Pointer): Integer; stdcall;
    procedure HeapMinimize; stdcall;
end;
在一些接口声明中,关键字interface被dispinterface代替。答案是这(还有dispid,read only,write only指定)和特殊平台有关,在Linux编程中不使用。

还有帮助以外的个人一些见解:接口也用来解决多重继承带来的混乱问题。Delphi中一个派生类只能继承一个类,但同时能继承多个接口。

PS: 关于数组属性的释疑,同样来自Delphi Help, 关键字Array properties
请先看例子:
    property Strings[Index: Integer]: string  ...; default;
这样也我们就可以用object[index]来代替object.property[index];但是也要注意,象这样的属性只能存在一个,不然大家也知道会发生什么事情了。

原创粉丝点击