Delphi接口

type IInterface = interface ['{00000000-0000-0000-C000-000000000046}'] //接口的GUID function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; end; IUnknown = IInterface;

可以看出来接口定义来自于Microsoft的组件对象模型(COM)规范;接口有一个唯一的GUID;同时,实现接口的类必须实现这个接口的三个方法,这些使得Delphi接口不同于Java和C#接口。如果要自定义一个接口并实现,那么你可以从TInterfacedObject继承,TInterfacedObject缺省实现了这个三个方法,比如:

unit Unit2; interface type IMyInterface = interface(IInterface) ['{2F1C697F-875E-410D-A415-AE9C7E79AFC0}'] //在Delphi的IDE中,按Ctrl+Shift+G键可以为一个接口生成一个新的GUID。 function Test: string; end; TMyObject = class(TInterfacedObject, IMyInterface) // 继承TInterfacedObject 并实现IMyInterface public function Test: string; end; implementation { TMyObject } function TMyObject.Test: string; begin Result := ClassName; end; end.

使用接口:

uses Unit2; procedure TForm1.Button1Click(Sender: TObject); var MyI: IMyInterface; begin MyI := TMyObject.Create; ShowMessage(MyI.Test); // 显示TMyObject // 接口是生存期自管理类型,不用显示释放。 end;

为什么要使用接口?套用一句话:对抽象编程。接口就是一种抽象,定义了一个约束,具体的实现留给实现接口的类。

你可能感兴趣的:(String,function,Microsoft,Integer,Delphi,interface)