匿名方法作为函数结果

编程入门 行业动态 更新时间:2024-10-25 10:21:46
本文介绍了匿名方法作为函数结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想要做的是将一个匿名方法(作为函数结果我将它分配给相同类型的变量)。 Delphi抱怨无法完成分配任务。显然,Delphi的东西我想分配 GetListener函数而不是该函数的结果。非常感谢对此的任何帮助。

What I want to do is to assign an anonymous method which I get as a function result to a variable of the same type. Delphi complains about not beeing able to do the assignement. Obviously Delphi things I want to assign the "GetListener" function instead of the result of that same function. Any help with this is very much appreciated.

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分配之间的区别:

I have written the following example to make clear the difference between the MyClass.GetListener() and MyClass.GetListener assignments:

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;

更多推荐

匿名方法作为函数结果

本文发布于:2023-10-18 13:22:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504343.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!