How to convert classname as string to a class?

后端 未结 4 1936
春和景丽
春和景丽 2021-01-03 03:42

I have classnames in a stringlist. For example it could be \'TPlanEvent\', \'TParcel\', \'TCountry\' etc.

Now I want to find out the sizes by looping the list.

相关标签:
4条回答
  • 2021-01-03 04:12
    1. You have to use FindClass to find the class reference by its name. If class is not found, then the exception will be raised.
    2. Optionally, you have to call RegisterClass for your classes, if they are not referenced explicitly in the code.
    0 讨论(0)
  • 2021-01-03 04:18

    If your classes derive from TPersistent you can use RegisterClass and FindClass or GetClass . Otherwise you could write some kind of registration mechanism yourself.

    0 讨论(0)
  • 2021-01-03 04:20

    In Delphi 2010 you can use:

    function StringToClass(AName: string): TClass;
    var
      LCtx: TRttiContext;
      LTp: TRttiType;
    begin
      Result := nil;
    
      try
        LTp := LCtx.FindType(AClassName);
      except
        Exit;
      end;
    
      if (LTp <> nil) and (LTp is TRttiInstanceType) then
        Result := TRttiInstanceType(LTp).Metaclass;
    end;
    

    One note. Since you only keep the class names in the list this method will not work because TRttiContext.FindType expects a fully qualified type name (ex. uMyUnit.TMyClass). The fix is to attach the unit where you store these classes in the loop or in the list.

    0 讨论(0)
  • 2021-01-03 04:21

    Since you're using a stringlist you can store the classes there, too:

    var
      C: TClass;
    
      StringList.AddObject(C.ClassName, TObject(C));
    

    ...

    for I := 0 to StringList.Count - 1 do
      Size := TClass(StringList.Objects[I]).InstanceSize;
    

    ...

    0 讨论(0)
提交回复
热议问题