正如我上面所说,声明一个接口并在 Delphi 端使用TdwsUnit 实现它是不可能的。但是,您可以通过其他方式实现您的目标。
我假设你已经在TdwsUnit 中声明了你的接口和你的类。我们称他们为IMyInterface 和TMyClass。
type
IMyInterface = interface
procedure SetValue(const Value: string);
function GetValue: string;
property Value: string read GetValue write SetValue;
procedure DoSomething;
end;
type
TMyClass = class(TObject)
protected
procedure SetValue(const Value: string);
function GetValue: string;
public
property Value: string read GetValue write SetValue;
procedure DoSomething;
end;
解决方案 1 - 在运行时更改类声明
为TdwsUnit.OnAfterInitUnitTable 事件创建一个事件处理程序并将接口添加到类声明中:
procedure TDataModuleMyStuff.dwsUnitMyStuffAfterInitUnitTable(Sender: TObject);
var
ClassSymbol: TClassSymbol;
InterfaceSymbol: TInterfaceSymbol;
MissingMethod: TMethodSymbol;
begin
// Add IMyInterface to TMyClass
ClassSymbol := (dwsUnitProgress.Table.FindTypeLocal('TMyClass') as TClassSymbol);
InterfaceSymbol := (dwsUnitProgress.Table.FindTypeLocal('IMyInterface') as TInterfaceSymbol);
ClassSymbol.AddInterface(InterfaceSymbol, cvProtected, MissingMethod);
end;
现在您可以通过脚本中的接口访问该类的实例:
var MyStuff: IMyInterface;
MyStuff := TMyObject.Create;
MyStuff.DoSomething;
解决方案 2 - 使用鸭式打字
由于 DWScript 支持duck typing,您实际上不需要声明您的类实现了接口。相反,您只需说明您需要什么接口,然后让编译器确定对象是否可以满足该需求:
var MyStuff: IMyInterface;
MyStuff := TMyObject.Create as IMyInterface;
MyStuff.DoSomething;