想不想get新技能酷炫一下,今天图老师小编就跟大家分享个简单的接口与类的区别教程,一起来看看吧!超容易上手~
【 tulaoshi.com - 编程语言 】
来自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];但是也要注意,象这样的属性只能存在一个,不然大家也知道会发生什么事情了。
来源:http://www.tulaoshi.com/n/20160219/1611809.html