2

我有两个组件 A 和 B。组件 B 派生自组件 A,并与它共享大多数属性和过程。现在我有一个像这样的冗长程序:

procedure DoSomething;
begin
  Form1.Caption := Component_A.Caption;
  // hundreds of additional lines of code calling component A
end;

根据组件 B 是否处于活动状态,我想重用上述过程并将 Component_A 部分替换为组件 B 的名称。它应该如下所示:

procedure DoSomething;
var
  C: TheComponentThatIsActive;
begin
  if Component_A.Active then
    C := Component_A;
  if Component_B.Active then
    C := Component_B;
  Form1.Caption := C.Caption;
end;

在Delphi2007中我怎么能做到这一点?

谢谢!

4

2 回答 2

4

TheComponentThatIsActive应该是与ComponentA( TComponentA) 相同的类型。

现在,如果您遇到一些属性/方法仅属于的绊脚石ComponentB,请检查并进行类型转换。

procedure DoSomething;
var
    C: TComponentA;

begin
    if Component_A.Active then
        C := Component_A
    else if Component_B.Active then
        C := Component_B
    else
        raise EShouldNotReachHere.Create();

    Form1.Caption := C.Caption;

    if C=Component_B then
        Component_B.B_Only_Method;
end;
于 2011-05-27T17:38:23.623 回答
2

您可以将 ComponentA 或 ComponentB 作为参数传递给 DoSomething。

ComponentA = class
public 
 procedure Fuu();
 procedure Aqq();
end;

ComponentB = class(ComponentA)
public 
 procedure Blee();
end;

implementation

procedure DoSomething(context:ComponentA);
begin
  context.Fuu();
  context.Aqq();
end;

procedure TForm1.Button1Click(Sender: TObject);
var cA:ComponentA;
    cB:ComponentB;
begin
  cA:= ComponentA.Create();
  cB:= ComponentB.Create();

  DoSomething(cA);
  DoSomething(cB);

  cA.Free;
  cB.Free;
end;
于 2011-05-27T18:20:57.137 回答