cast TObject using his ClassType?

前端 未结 5 1238
抹茶落季
抹茶落季 2021-01-13 07:27

how can i make my code to work ? :) i`ve tried to formulate this question but after several failed attempts i think you guys will spot the problem faster looking at the code

5条回答
  •  攒了一身酷
    2021-01-13 07:51

    You need to cast the ct object to a TMemo/TEdit/TButton before you can set properties on the object.

    The line where you're getting errors are erroring because ct is still a TClass, not a TButton/etc. If you cast to a TButton, then you'll be able to set enabled to true.

    I recommend reading up on casting in Delphi. Personally, I would recommend using the as/is operators instead of using ClassType, as well. The code will be simpler in that case, and much more understandable.


    Personally, I would write this more like:

    procedure setCtrlState(objs: array of TObject; bState: boolean = True);
    var
      obj: TObject;
    begin
      for obj in objs do
      begin
        // I believe these could be merged by using an ancestor of TMemo+TEdit (TControl?)
        // but I don't have a good delphi reference handy
        if (obj is TMemo) then
            TMemo(obj).ReadOnly := not bState;
    
        if (obj is TEdit) then
            TEdit(obj).ReadOnly := not bState;
    
        if (obj is TButton) then
            TButton(obj).Enabled := bState;
      end;
    end;
    

提交回复
热议问题