在Delphi中通过类名获取类

3
我可以帮助您翻译中文,本文涉及IT技术。您需要编写一个函数,它接受一个类名并返回相应的TClass。我注意到,如果未注册该类名,则System.Classes.GetClass函数不起作用。
例子:
if(GetClass('TButton') = nil)
then ShowMessage('TButton not found!')
else ShowMessage('TButton found!');

之前的代码总是显示:

找不到TButton!

有什么遗漏吗?
1个回答

9
您可以通过扩展的 RTTI 获取 Delphi 应用程序中使用的未注册类。但是,您必须使用完全限定的类名来查找类。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;

注册类可以确保该类被编译到Delphi应用程序中。如果该类在代码中没有被使用或未注册,它将不会出现在应用程序中,扩展的RTTI也无法使用。

另外,还有一个函数可以返回任何类(无论是否注册),而无需使用完全限定的类名:

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;

感谢您清晰而完整的回答。我想没有绕过使用完全限定类名的方法。 - Hwau
我已经添加了额外的函数,您可以使用它们而无需使用完全限定的类名。 - Dalija Prasnikar
太棒了!我不擅长使用 Rtti,我永远不会找到解决方案!非常感谢! - Hwau

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接