Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/delphi/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Delphi “这是什么问题?”;参考「;解决_Delphi_Generics_Anonymous Methods - Fatal编程技术网

Delphi “这是什么问题?”;参考「;解决

Delphi “这是什么问题?”;参考「;解决,delphi,generics,anonymous-methods,Delphi,Generics,Anonymous Methods,在Chris的博客上: 我找到了下面的代码 type TLinkVisitor<T> = reference to procedure(const Item: T); TDoubleLinked<T> = record Prev: ^TDoubleLinked<T>; Next: ^TDoubleLinked<T>; Value: T; class function Create(const aValue:

在Chris的博客上:

我找到了下面的代码

type
  TLinkVisitor<T> = reference to procedure(const Item: T);

  TDoubleLinked<T> = record
    Prev: ^TDoubleLinked<T>;
    Next: ^TDoubleLinked<T>;
    Value: T;
    class function Create(const aValue: T): Pointer; static;
    function Add(const aValue: T): Pointer;
    procedure Delete;
    procedure DeleteAll;
    function First: Pointer;
    function Last: Pointer;
    procedure ForEach(const Proc: TLinkVisitor<T>);
  end;
类型
TLinkVisitor=程序参考(常数项:T);
t双重链接=记录
上一页:^t已双击;
下一步:^t加倍链接;
值:T;
类函数Create(const aValue:T):指针;静止的
函数Add(const aValue:T):指针;
程序删除;
程序删除所有;
函数一:指针;
函数Last:指针;
程序ForEach(const Proc:TLinkVisitor);
结束;

“reference to”(参考)关键字解决了正常程序类型无法解决的问题?

对于
参考
程序,您可以使用:

  • 传统的程序,或
  • 对象、类或记录的方法,或
  • 匿名方法
它能够使用匿名方法,将
reference
过程与所有其他过程类型区分开来。将匿名方法与其他过程或方法类型区分开来的是变量捕获


有关更详细的讨论,请参阅以下答案:。匿名方法的官方文档也值得一读

根据官方文档,问题(待解决)在于匿名方法是托管类型,而过程变量不是。
“reference to”关键字比其他过程类型更通用

医生是这样说的:

匿名方法通常分配给某个对象,如以下示例所示:

匿名方法也可以由函数返回,或者在调用方法时作为参数值传递。例如,使用上面定义的匿名方法变量myFunc:

方法引用也可以分配给方法以及匿名方法。例如:

然而,反之则是而非真:不能将匿名方法分配给常规方法指针。方法引用是托管类型,但方法指针是非托管类型。因此,出于类型安全原因,不支持将方法引用分配给方法指针。例如,事件是方法指针值属性,因此不能对事件使用匿名方法。有关此限制的更多信息,请参阅变量绑定部分


您缺少匿名方法最重要的关键特性之一,即变量捕获。其他的事情,比如传递或返回它们,可以用常规的函数指针来完成,但是变量捕获不能。感谢@StefanGlienke指出这一点。我都忘了。当然,堆上发生的所有这些幻想排除了高速代码的这种可能性。
myFunc := function(x: Integer): string
begin
  Result := IntToStr(x);
end;

myProc := procedure(x: Integer)
begin
  Writeln(x);
end;
type
  TFuncOfIntToString = reference to function(x: Integer): string; 

procedure AnalyzeFunction(proc: TFuncOfIntToString); 
begin 
  { some code } 
end;

// Call procedure with anonymous method as parameter 
// Using variable: 
AnalyzeFunction(myFunc);

// Use anonymous method directly: 
AnalyzeFunction(function(x: Integer): string 
begin 
  Result := IntToStr(x); 
end;) 
type
  TMethRef = reference to procedure(x: Integer);
TMyClass = class
  procedure Method(x: Integer);
end;

var
  m: TMethRef;
  i: TMyClass;
begin
  // ...
  m := i.Method;   //assigning to method reference
end;