以下示例显示如何开始对接口进行编码:
从
TMyObject = class
function Add(a, b: integer): integer;
end;
Run Code Online (Sandbox Code Playgroud)
至
IInterface = interface
['{BFC7867C-6098-4744-9774-35E0A8FE1A1D}']
function Add(a, b: integer): integer;
end;
TMyObject = class (TInterfacedObject, IInterface
function Add(a, b: integer): integer;
end;
Run Code Online (Sandbox Code Playgroud)
但如果该类有一个祖先,我怎么能管理,比如说TMyClassDerivedDirectlyFromTObjectSoItsGotNothingInItAtAll?
TMyObject = class(TMyClassDerivedDirectlyFromTObjectSoItsGotNothingInItAtAll)
function Add(a, b: integer): integer;
end;
Run Code Online (Sandbox Code Playgroud)
当你有一个实现接口的类时,这个类必须提供三个方法:_AddRef,_Release和QueryInterface.如果你看一下TInterfacedObject代码,你会发现那些方法.实际上,仅存在TInterfacedObject以便更容易创建新的接口实现器类.
如果您无法从TInterfacedObject继承新类,则必须自己提供这些方法.例如,您可以将TInterfacedObject实现复制到您的类中,然后您的类将成为接口实现者.