How to convert classname as string to a class?

◇◆丶佛笑我妖孽 提交于 2019-11-30 17:46:14

问题


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.

It works to have:

Size := TCountry.InstanceSize;

But I want it like this:

for i := 0 to ClassList.Count - 1 do
  Size := StringToClass(ClassList[i]).InstanceSize;

Obviously my question is what to write instead of method StringToClass to convert the string to a class.


回答1:


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;

...




回答2:


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




回答3:


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.




回答4:


  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.


来源:https://stackoverflow.com/questions/2727654/how-to-convert-classname-as-string-to-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!