开发者

Delphi 2009 - Detect if component installed

I got some code that I share with another developer. I have a nice debugging module which I leave through out the unit tests but he doesn't have this, so it's a battle of adding and remove the code constantly.

Would be nice if there was a way we could use a condition (much like Delphi version or Unicode) like

  {$IfDef MYComponent}
    MyComponent 开发者_如何学Python:= TMyComponent.Create;
    MyComponent.Logging := true;
  {$EndIf}

I guess I could set my ide to Define something, but I wonder if there is a way to detect if the component is installed.....


Try this (which should work in all versions since Delphi 6):

{$IF DECLARED(TMyComponent)}
{$IFEND}

You can then simply update your uses list to make that component visible or not.


You can have him use a component unit that only has stub implementations. eg:

type
  TMyComponent = class
    procedure DoSomething();
  end;

procedure TMyComponent.DoSomeThing();
begin
  //no-op
end;

If you want to use different unit names you can use the unit alias option from Delphi located in your project options -> Directories and conditionals -> Unit aliases: add an alias for unit UnitMyComponent -> UnitDummyMyComponent.

You now can use code that is at least ifdef free!


Not exactly ifdefs, but you can use the class inheritance and testing against assigned to see if you should take an action. You would still want to have some sort of proxy setup, so that both you and the other developer can compile...just your version has the added target of the proxy. For example:

In the "shared" unit that both developers would have would be something like this:

type
  TMyComponent = class
  public
    procedure DoSomething; virtual;
  end;

var
  MyComponent : TMyComponent;

procedure TMyComponent.DoSomething;
begin
  // stubbed
end;

in your "special" unit you would have the following code:

type
  TMyRealComponent = Class(tMyComponent)
  public
    procedure DoSomething; override;
  end;

procedure TMyRealComponent.DoSomething;
begin
  // do the real process here
end;

initialization
  MyComponent := TMyRealComponent.Create;
finalization
  if Assigned(MyComponent) then
    MyComponent.Free;
end.

In your code when you want to see if its ok to do something you can write:

if Assigned(MyComponent) then
  MyComponent.DoSomething;

If you want to disable this debug code, then remove the special unit from the project.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜