我想要做的是将一个匿名方法作为函数结果分配给相同类型的变量.德尔福抱怨说不能做出任命.显然Delphi的东西我想分配“GetListener”函数而不是相同函数的结果.非常感谢任何帮助. ty
type TPropertyChangedListener = reference to procedure (Sender: TStimulus); TMyClass = class function GetListener:TPropertyChangedListener end; .... var MyClass: TMyClass; Listener: TPropertyChangedListener; begin MyClass:= TMyClass.create; Listener:= MyClass.GetListener; // Delphi compile error: E2010 Incompatible types: TPropertyChangedListener' and 'Procedure of object' end;使用以下语法:
Listener:= MyClass.GetListener();
我编写了以下示例以明确MyClass.GetListener()和MyClass.GetListener分配之间的区别:
type TProcRef = reference to procedure(Sender: TObject); TFunc = function: TProcRef of object; TMyClass = class function GetListener: TProcRef; end; function TMyClass.GetListener: TProcRef; begin Result:= procedure(Sender: TObject) begin Sender.Free; end; end; procedure TForm1.Button1Click(Sender: TObject); var MyClass: TMyClass; ProcRef: TProcRef; Func: TFunc; begin MyClass:= TMyClass.Create; // standard syntax ProcRef:= MyClass.GetListener(); // also possible syntax // Func:= MyClass.GetListener; // ProcRef:= Func(); ProcRef(MyClass); end;