[Lazarus] how to get Type of Sender or Components[i] in order to Cast?

Michael Van Canneyt michael at freepascal.org
Mon Jul 27 11:39:26 CEST 2015



On Mon, 27 Jul 2015, Mark Morgan Lloyd wrote:

> JuuS wrote:
>> On 07/27/2015 09:31 AM, Mark Morgan Lloyd wrote:
>>> Péter Gábor wrote:
>>>> Sorry!
>>>> I was "misreading" your mail... you want to know the type of them.
>>>> 
>>>> You can compare the type of them:
>>>> 
>>>> if Sender = TButton then { do something} ;
>>> Can this be elegantly put into a case statement?
>>> 
>> Hi, I just tried it and no you can't. At least not directly, there may
>> be a way of casting the Sender object to ordinal or string but I'm not
>> sure that is efficient or elegant.
>
> I didn't think there was, but thought it worth asking. My use case is this 
> sort of thing:
>
>        if MainForm.OutputComponent is TListBox then
>          with MainForm.ListBox1 do begin
>            Font.Name := fontName;
>            Font.Size := fontSize
>          end;
>        if MainForm.OutputComponent is TMemo then
>          with MainForm.Memo1 do begin
>            Font.Name := fontName;
>            Font.Size := fontSize
>          end;
>        ...
>
> Now obviously I could have a separate property holding an enumeration, but 
> it's a pity that it's not possible to do something like
>
>        case MainForm.OutputComponent of
>          TListBox: begin end;
>          TMemo:    begin end;
>          ...
>        otherwise
>          // Fatal exception since this is a serious programming error
>        end;

You can:
   Case Lowercase(MainForm.OutputComponent.Classname) of
     'tlistbox' : begin end;
     'tmemo' : begin end;

Michael.


More information about the Lazarus mailing list