最小化/优化重复代码

时间:2012-05-19 09:25:54

标签: delphi delphi-2010

这是我的代码,当鼠标光标悬停在TPanel上时,它会“动画化”procedure Tmain.pStarting1MouseEnter(Sender: TObject); begin if sender = pStarting1 then pStarting1.BevelInner := bvLowered; if sender = pStarting2 then pStarting2.BevelInner := bvLowered; if sender = pStarting3 then pStarting3.BevelInner := bvLowered; if sender = pStarting4 then pStarting4.BevelInner := bvLowered; if sender = pStarting5 then pStarting5.BevelInner := bvLowered; if sender = pStarting6 then pStarting6.BevelInner := bvLowered; if sender = pStarting7 then pStarting7.BevelInner := bvLowered; if sender = pStarting8 then pStarting8.BevelInner := bvLowered; if sender = pStarting9 then pStarting9.BevelInner := bvLowered; end; 。我还有一个代码块来实现它。

TPanel

正如你所看到的,它非常重复,因为我有另外27个sender来制作动画,这意味着另外27行重复代码。那么有什么方法可以优化它?

我还尝试将该代码块放入一个单独的程序中(在同一单元中)。但是Delphi告诉我{{1}}未声明。

2 个答案:

答案 0 :(得分:11)

if Sender is TPanel then
  TPanel(Sender).BevelInner := bvLowered;

或者,如果您确定Sender始终是TPanel,则只需

(Sender as TPanel).BevelInner := bvLowered;

或(如果你确实确定)

TPanel(Sender).BevelInner := bvLowered;

答案 1 :(得分:1)

利用absolute关键字,还有第四种方法。

procedure Tmain.pStarting1MouseEnter(Sender: TObject);
var
    Panel: TPanel absolute Sender;

begin
    if Sender is TPanel then
        Panel.BevelInner := bvLowered;
end;