什么是两者之间的区别?
TFuncOfIntToString = reference to function(x: Integer): string;
和
TFuncOfIntToString = function(x: Integer): string of object;
我使用对象的of属性
什么是两者之间的区别?
TFuncOfIntToString = reference to function(x: Integer): string;
和
TFuncOfIntToString = function(x: Integer): string of object;
我使用对象的of属性
让我们考虑以下三种类型声明:
TProcedure = procedure;
TMethod = procedure of object;
TAnonMethod = reference to procedure;
procedure MyProcedure;
begin
end;
TProcedure
变量。但是,你可以将静态类方法赋给TProcedure
变量。
方法指针
TMethod
是一个方法指针,它通过of object
来表示。当你有一个TMethod
类型的变量时,你必须分配以下之一:
procedure TMyClass.MyMethod;
begin
end;
class procedure TMyClass.MyClassMethod;
begin
end;
过程类型和方法指针之间的主要区别在于,后者包含对代码和数据的引用。方法指针通常被称为双指针过程类型。包含方法指针的变量包含对要调用的代码和实例/类的引用。
考虑以下代码:
var
instance1, instance2: TMyClass;
method1, method2: TMethod;
....
method1 := instance1.MyMethod;
method2 := instance2.MyMethod;
method1
和method2
引用相同的代码段,但它们与不同的对象实例相关联。因此,如果我们调用method1();
method2();
MyMethod
。该代码等效于:instance1.MyMethod();
instance2.MyMethod();
匿名方法
最后我们来到匿名方法。它们比过程类型和方法指针更加通用。您可以将以下任何内容分配给使用引用到
语法定义的变量:
例如:
var
AnonMethod: TAnonMethod;
....
AnonMethod := MyProcedure; // item 1 above
AnonMethod := instance1.MyMethod; // item 2
AnonMethod := TMyClass.MyClassMethod; // item 3
匿名方法,即上面提到的第4种方法,是在代码中内联声明的方法。例如:
var
AnonMethod: TAnonMethod;
....
AnonMethod := procedure
begin
DoSomething;
end;
{$APPTYPE CONSOLE}
program VariableCapture;
type
TMyFunc = reference to function(X: Integer): Integer;
function MakeFunc(Y: Integer): TMyFunc;
begin
Result := function(X: Integer): Integer
begin
Result := X*Y;
end;
end;
var
func1, func2: TMyFunc;
begin
func1 := MakeFunc(3);
func2 := MakeFunc(-42);
Writeln(func1(4));
Writeln(func2(2));
Readln;
end.
12 -84