我有一个接口(实际上是多个接口),我想这样使用:
是否有可能这样做?
我试图在类中提供返回这些接口的方法,但是当我在RTTI上使用这个类时,没有找到这些方法。
发布于 2015-09-13 11:55:56
正如我前面所述,不可能立即声明接口并使用TdwsUnit实现Delphi。然而,以其他方式达到你所追求的目标是可能的。
我假设您已经在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支持鸭型,所以实际上不需要声明您的类实现了接口。相反,您只需说明所需的接口,并让编译器确定对象是否能够满足该需要:
var MyStuff: IMyInterface;
MyStuff := TMyObject.Create as IMyInterface;
MyStuff.DoSomething;https://stackoverflow.com/questions/32545055
复制相似问题