在 Delphi 中按名称获取 class

Get class by its name in Delphi

我想编写一个接受类名并生成相应 TClass 的函数。我注意到,如果类名未注册,System.Classes.GetClass 函数将不起作用。

示例:

if(GetClass('TButton') = nil)
then ShowMessage('TButton not found!')
else ShowMessage('TButton found!');

之前的代码总是显示:

TButton not found!

是不是少了什么?

您可以通过扩展 RTTI 在 Delphi 应用程序中使用未注册的 class。但是您必须使用完全限定的 class 名称才能找到 class。 TButton 不够,你必须搜索 Vcl.StdCtrls.TButton

uses
  System.Classes,
  System.RTTI;

var
  c: TClass;
  ctx: TRttiContext;
  typ: TRttiType;
begin
  ctx := TRttiContext.Create;
  typ := ctx.FindType('Vcl.StdCtrls.TButton');
  if (typ <> nil) and (typ.IsInstance) then c := typ.AsInstance.MetaClassType;
  ctx.Free;
end;

注册 class 确保 class 将被编译到 Delphi 应用程序中。如果 class 未在代码中的任何地方使用且未注册,则它不会出现在应用程序中,扩展的 RTTI 在这种情况下将有任何用处。

附加功能将 return 任何 class(已注册或未注册)而不使用完全限定的 class 名称:

uses
  System.StrUtils,
  System.Classes,
  System.RTTI;

function FindAnyClass(const Name: string): TClass;
var
  ctx: TRttiContext;
  typ: TRttiType;
  list: TArray<TRttiType>;
begin
  Result := nil;
  ctx := TRttiContext.Create;
  list := ctx.GetTypes;
  for typ in list do
    begin
      if typ.IsInstance and (EndsText(Name, typ.Name)) then
        begin
          Result := typ.AsInstance.MetaClassType;
          break;
        end;
    end;
  ctx.Free;
end;