在Delphi中以名字命名

时间:2015-04-06 12:58:15

标签: class delphi get classname

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

示例:

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

前面的代码总是显示:

  

没找到TButton!

有什么遗失吗?

1 个答案:

答案 0 :(得分:6)

您可以通过扩展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;
相关问题