我想声明一个通用记录,如下所示:
type
TMyDelegate<T: constraint> = record
private
fDelegate: T;
public
class operator Implicit(a: T): TMyDelegate;
class operator Implicit(A: TMyDelegate: T);
end;
我想将T
限制为对过程/函数的引用
。 (越多越好)。
我已经尝试过这个,但它无法编译:
program Project3;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
type
TProc1 = reference to procedure(a: Integer);
TProc2 = reference to procedure(b: TObject);
TTest<T: TProc1, TProc2> = record
private
fData: T;
public
class operator Implicit(a: T): TTest<T>;
class operator Implicit(a: TTest<T>): T;
end;
{ TTest<T> }
class operator TTest<T>.Implicit(a: T): TTest<T>;
begin
Result.fData:= a;
end;
class operator TTest<T>.Implicit(a: TTest<T>): T;
begin
Result:= a.fData;
end;
var
Delegate1: TProc1;
Delegate2: TProc2;
var
MyTest1: TTest<TProc1>; <<-- error
MyTest2: TTest<TProc2>;
begin
MyTest1:=
procedure(a: Integer)
begin
WriteLn(IntToStr(a));
end;
end.
这会产生编译错误:
[dcc32 Error] Project3.dpr(39): E2514 Type parameter 'T' must support interface 'TProc2'
有没有办法将泛型类型限制为匿名类型(列表)?
最佳答案
大卫的答案是正确的,但作为解决类似问题的方法可能会有所帮助:
program Project51;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
type
TTest<T> = record
type
TProcT = reference to procedure(a: T);
private
fData: TProcT;
public
class operator Implicit(a: TProcT): TTest<T>;
class operator Implicit(a: TTest<T>): TProcT;
end;
{ TTest<T> }
class operator TTest<T>.Implicit(a: TProcT): TTest<T>;
begin
Result.fData:= a;
end;
class operator TTest<T>.Implicit(a: TTest<T>): TProcT;
begin
Result:= a.fData;
end;
var
MyTest1: TTest<Integer>;
MyTest2: TTest<TObject>;
begin
MyTest1:=
procedure(a: Integer)
begin
WriteLn(IntToStr(a));
end;
MyTest2:=
procedure(a: TObject)
begin
WriteLn(a.ClassName);
end;
end.
关于delphi - 我对匿名方法类型使用什么通用约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24814068/