1. 程式人生 > >(sender as TButton).some 和 TButton(sender).some 的區別是什麽?

(sender as TButton).some 和 TButton(sender).some 的區別是什麽?

rms call 執行 edi ... implement 正在 imp custom

(sender as TButton).some 和 TButton(sender).some 的區別是什麽?

(Sender as TButton) 與 TButton(Sender) 都是 Typecasting,只是語法不同
罷了, 因此, 寫成 (Sender as TButton).Caption := ‘Test‘;或者
TButton(Sender).Caption := ‘Test‘;
結果都一樣
針對個別物件個別事件寫事件處理程序, 並不需判定 Sender為何, 因為很明
顯的 Sender便是這個正在撰寫的物件, 但是在多個物件共用一個事件處理程序的情況下,Sender 是誰(誰發生OnClick事件)的判斷就有其必要性

if Sender = Button1 的寫法是直接判定Sender是不是 Button1這個物件, 但是如果按鈕有 64 個, 寫 64 個 if敘述恐怕會累死人的...
因此, 以類別的判定取代個別物件的副本(instance)的判定, 應是比較簡明的
作法, 於是, 我們可以寫成 Sender is TButton, 為真時, 以上述型別轉換的方式 --- TButton(Sender).XXXX 撰寫, 就可以大輻簡化程式,
畢竟,同屬 TButton 的物件, 都有相同的屬性(屬性值不一定相同), 不是嗎?
值得註意的是, Sender is (Class Name) 的 Class Name 判斷是會牽涉到父階的繼承關系的, 例如: Button1 是Button,Button2是 TBitBtn, 這樣的話:Button1 is TButton 為真, Button2 is TButton 也是真, 因為TBitBtn 繼承自TButton, 也就是說, 球是球, 籃球也是球. 應用這個觀念, 下列的程式:
if ActiveControl is TDBEdit then
(ActiveControl as TDBEdit).CutToClipboard
else
if ActiveControl is TDBMemo then
(ActiveControl as TDBMemo).CutToClipboard;
如果改成:
if ActiveControl is TCustomMemo then
TCustomMemo(ActiveControl).CutToClipboard;
程序的執行效率就更好了, 因為 TDbEdit 與 TDbMemo 的共同父階是
TCustomMemo, 而 TCustomMemo
也有 CutToClipboard 方法

有沒有試一下我的例子,就知道了。
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TA = class
public
procedure Test;
end;

TB = class(TA)
public
procedure Test;
procedure Test1;
procedure Test2;
end;

TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TA.Test;
begin
Showmessage(‘Call TA.test‘);
end;

procedure TB.Test;
begin
Showmessage(‘Call TB.test‘);
end;

procedure TB.Test1;
begin
(self as TA).test;
end;

procedure TB.Test2;
begin
TA(self).test;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin

with TB.Createdo
begin
test1;
free;
end;

{
with TB.Createdo
begin
test2;
free;
end;
}
end;

end.

www:
如果sender 與 TButton 沒有關系,編譯照樣不通過。

(sender as TButton).some 和 TButton(sender).some 的區別是什麽?