避免在Delphi中重复代码

| 我有两个组件A和B。组件B派生自组件A,并与它共享大多数属性和过程。现在,我有一个冗长的过程,例如:
procedure DoSomething;
begin
  Form1.Caption := Component_A.Caption;
  // hundreds of additional lines of code calling component A
end;
根据组件B是否处于活动状态,我想重复使用上述过程,并用组件B的名称替换Component_A部分。然后,它应如下所示:
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中做到这一点? 谢谢!     
已邀请:
        
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;
    
        您可以将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;
    

要回复问题请先登录注册