cast TObject using his ClassType?

前端 未结 5 1230
抹茶落季
抹茶落季 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:50

    You must explicitly cast object to some class. This should work:

     procedure setCtrlState(objs: array of TObject; bState: boolean = True);
     var
       obj: TObject;
       ct: TClass;
     begin
      for obj in objs do
      begin
        ct := obj.ClassType;
    
        if ct = TMemo then
          TMemo(obj).ReadOnly := not bState
        else if ct = TEdit then
          TEdit(obj).ReadOnly := not bState
        else if ct = TButton then
          TButton(obj).Enabled := bState;
      end;
    end;
    

    This can be shortened using "is" operator - no need for ct variable:

     procedure setCtrlState(objs: array of TObject; bState: boolean = True);
     var
       obj: TObject;
     begin
       for obj in objs do
       begin
         if obj is TMemo then
           TMemo(obj).ReadOnly := not bState
         else if obj is TEdit then
           TEdit(obj).ReadOnly := not bState
         else if obj is TButton then
           TButton(obj).Enabled := bState;
       end;
     end;
    

提交回复
热议问题