我试图将表达式作为参数传递给Delphi 10.2中的函数或过程,
function Where(exp:TExp):TLinq;
我想这样称呼它:
r := Where(Product.ID=Command.ProductID);
我可以在delphi中做到这一点吗,以及如何拦截该表达式;
答案 0 :(得分:2)
否,您不能直接使用表达式 作为参数。
您可以改用anonymous method:
function Where(exp: TFunc<Boolean>): TLinq;
...
r := Where(
function: Boolean
begin
Result := Product.ID = Command.ProductID;
end
);
更新:或者,如果您确实想要更LINQ风格的语法,则可以使用enhanced records和operator overloading来实现,例如:
type
Operand = record
Value: Variant;
class operator Implicit(const a: Variant): Operand;
class operator Equal(const a, b: Operand): Boolean;
// other operators as needed...
end;
Expression = record
Value: Boolean;
class operator Implicit(const a: Boolean): Expression;
// other operators as needed...
end;
class operator Operand.Implicit(const a: Variant): Operand;
begin
Result.Value := a;
end;
class operator Operand.Equal(const a, b: Operand): Boolean;
begin
Result := a.Value = b.Value;
end;
// ...
class operator Expression.Implicit(const a: Boolean): Expression;
begin
Result.Value := a;
end;
// ...
function Where(exp: Expression): TLinq;
begin
// use exp.Value as needed...
end;
type
TProduct = record
ID: Integer;
end;
TCommand = record
ProductID: Integer;
end;
var
Product: TProduct;
Command: TCommand;
begin
Product.ID := 1;
Command.ProductID := 1;
Where(Product.ID = Command.ProductID);
Product.ID := 1;
Command.ProductID := 2;
Where(Product.ID = Command.ProductID);
...
end;