我想编写一个接受类名并产生相应结果的函数TClass
。我注意到,System.Classes.GetClass
如果类名未注册,该函数将不起作用。
Example:
if(GetClass('TButton') = nil)
then ShowMessage('TButton not found!')
else ShowMessage('TButton found!');
前面的代码总是显示:
未找到 TButton!
是不是少了点什么?
您可以通过扩展 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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)