在Delphi中以名字命名

Hwa*_*wau 3 delphi get class classname

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

例:

if(GetClass('TButton') = nil)
then ShowMessage('TButton not found!')
else ShowMessage('TButton found!');
Run Code Online (Sandbox Code Playgroud)

以前的代码总是显示:

没找到TButton!

有什么遗失的吗?

Dal*_*kar 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;
Run Code Online (Sandbox Code Playgroud)

注册类确保将类编译到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;
Run Code Online (Sandbox Code Playgroud)