2017-09-23 194 views
-5

我想利用可變類類型,以儘量減少此代碼,它是從屬性和事件:可變類創建

if ctype='T' then 
begin 
    C:= TTimeEdit.Create(self); 
    (c as TTimeEdit).OnMouseUp:= Panel2MouseUp; 
    (c as TTimeEdit).OnMouseDown:= Panel2MouseDown; 
    (c as TTimeEdit).OnMouseMove:= Panel2MouseMove; 
    (c as TTimeEdit).PopupMenu:= PopupMenu1; 
end; 

if ctype='S' then 
begin 
    C:= TTabSheet.Create(self); 
    (c as TTabSheet).OnMouseUp:= Panel2MouseUp; 
    (c as TTabSheet).OnMouseDown:= Panel2MouseDown; 
    (c as TTabSheet).OnMouseMove:= Panel2MouseMove; 
    (c as TTabSheet).PopupMenu:= PopupMenu1; 
end; 

看起來像這樣:

VAR VARCLS:TCLASS; 
BEGIN 
    if ctype='S' then 
    VARCLS:=TTabSheet; 
    if ctype='T' then 
    VARCLS:=TTimeEdit; 
    C:= VARCLS.Create(self); 
    (c as VARCLS).OnMouseUp:= Panel2MouseUp; 
    (c as VARCLS).OnMouseDown:= Panel2MouseDown; 
    (c as VARCLS).OnMouseMove:= Panel2MouseMove; 
    (c as VARCLS).PopupMenu:= PopupMenu1; 
end; 

確保代碼要長得多比這個,但我用了一個樣本!

+1

使用RTTI來實現這個 –

+3

我想要一隻小馬:-)你真的需要問一個實際的問題,而不是給出一個需求列表。你試過什麼了?你從哪裏被困住了? –

+1

如果所有類都有一個共同的父類,並且來自該類的所有事件(就像您的情況一樣),只需創建一個'程序AssignEvents(const AObject:TWinControl);'並在其中設置所需的事件。無需單獨投射。對於FMX你可能需要TControl。只是一個樣本。 – Marcodor

回答

2

有兩種方法可以做到這一點:

如果類有一個共同的祖先(很可能爲VCL或FMX類),那麼你可以只使用一個class of TAncestor並創建該類的一個特定實例。

參見:http://docwiki.embarcadero.com/RADStudio/Seattle/en/Class_References#Constructors_and_Class_References

假設你正在使用VCL,它幾乎是用FMX 有一個警告的TControl事件受到保護一樣,但我們可以用一箇中介類要解決這個問題。

type 
    TMyClass = class of TControl; 

//interposer class, makes events public; 

TPublicControl = class(TControl) 
public 
    property OnMouseUp;  //a 'naked' property redeclares the existing 
    property OnMouseDown; //events and properties as public 
    property OnMouseMove; 
    property PopupMenu; 
end; 

function CreateThing(Owner: TControl; MyType: TMyClass): TControl; 
begin 
    Result:= MyType.Create(Owner); 
    TPublicControl(Result).OnMouseUp:= Panel2MouseUp; 
    .... 
end; 

該例程不必知道類型,仍然返回一個特定的創建實例。

你調用這個例程,像這樣:

var 
    MyEdit: TEdit; 
begin 
    MyEdit:= TEdit(CreateThing(Panel, TEdit)); 

另一種方法是使用RTTI,但我不會推薦,除非你使用的是沒有一個共同的祖先對象。
如果您確實如此,請告訴我,我會擴大答案。

+0

@RobKennedy修好了,謝謝 – Johan

+0

這樣解決了這個問題,謝謝。 – JIMMY