如何根据枚举类型信息调用重载函数?

时间:2014-08-06 10:08:24

标签: delphi typeinfo

我想为几个TImages画一些主题部分。在下面的代码中,GetElementDetails需要一定的枚举值。我有枚举类型的PTypeInfo,但我不知道如何为枚举类型输入i

procedure TForm1.Button1Click(Sender: TObject);
  procedure drawType(c: tcanvas; ti: ptypeinfo);
  var
    r: trect;
    i: integer;
    details: TThemedElementDetails;
  begin
    r.Left := 0; r.Top := 0; r.Right := 19; r.Bottom := 19;
    for i := GetTypeData(ti).MinValue to GetTypeData(ti).MaxValue do begin
      // How to cast i to the enum type of ti?
      details := StyleServices.GetElementDetails( ???(i) );

      StyleServices.DrawElement(c.Handle, details, R);
      if (i mod 10 = 0) and (i > 0) then begin
        r.Left := 0; r.Right := 19; r.Top := r.Bottom + 3; r.Bottom := r.Bottom + 22;
      end
      else r.Inflate(-22,0,22,0);
    end;
  end;
begin
  drawType(image1.canvas, typeinfo(TThemedToolBar));
  drawType(image2.canvas, typeinfo(TThemedButton));
  drawType(image3.canvas, typeinfo(TThemedCategoryPanelGroup));
  drawType(image4.canvas, typeinfo(TThemedComboBox));
end;

我需要将i转换为作为第二个变量传递的类型(TThemedToolBarTThemedButton等)。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:4)

试试这个:

type
   TAbstractStyleServicesFunction = reference to function(const styleServices: TAbstractStyleServices; const I: Integer)
      : TThemedElementDetails;


procedure TForm1.drawType(c: TCanvas; ti: PTypeInfo; const styleServicesFunction: TAbstractStyleServicesFunction);
var
   r: trect;
   I: Integer;
begin
   r.Left := 0;
   r.Top := 0;
   r.Right := 19;
   r.Bottom := 19;
   for I := GetTypeData(ti).MinValue to GetTypeData(ti).MaxValue do
   begin
      styleServices.DrawElement(c.Handle, styleServicesFunction(styleServices, I), r);

      if (I mod 10 = 0) and (I > 0) then
      begin
         r.Left := 0;
         r.Right := 19;
         r.Top := r.Bottom + 3;
         r.Bottom := r.Bottom + 22;
      end
      else
         r.Inflate(-22, 0, 22, 0);
   end;
end;



procedure TForm1.Button1Click(Sender: TObject);
begin
   drawType(image1.canvas, typeinfo(TThemedToolBar),
      function(const styleServices: TAbstractStyleServices; const I: Integer): TThemedElementDetails
      begin
         Result := styleServices.GetElementDetails(TThemedToolBar(I));
      end);
end;

答案 1 :(得分:2)

你不能轻易做到这一点。 GetElementDetails方法在其第一个参数上严重超载。重载分辨率是静态的,在编译时执行。您希望在运行时根据枚举的运行时类型绑定到方法。这对普通的方法调用是不可能的。

执行此操作的唯一方法是使用RTTI。枚举样式服务对象的方法。找到名称为GetElementDetails的所有名称。选择其参数与枚举的运行时类型匹配的那个。然后使用RTTI调用它。

我无法编写任何代码来向您展示这一点,但是现在您知道需要做什么,这些技术有很多很好的例子。