在Delphi中通过它的名称获取类 [英] Get class by its name in Delphi
问题描述
我想写一个函数接受一个类名,并得到相应的TClass。我注意到,如果没有注册类名,System.Classes.GetClass函数不工作。
I would like to write a function that accepts a classname and results the corresponding TClass. I've noticed that, System.Classes.GetClass function doesn't works if the classname isn't registered.
示例:
if(GetClass('TButton') = nil)
then ShowMessage('TButton not found!')
else ShowMessage('TButton found!');
前面的代码总是显示TButton not found!
是否有缺少的东西?
希望有人可以帮助我。
谢谢!
The previous code always shows 'TButton not found!'. Is there something missing? Hope someone can help me. Thanks!
推荐答案
您可以通过扩展RTTI获取Delphi应用程序中使用的未注册类。但是你必须使用完全限定类名来查找类。 TButton
还不够,您必须搜索 Vcl.StdCtrls.TButton
You can get unregistered class used in Delphi application via extended RTTI. But you have to use fully qualified class name to find the class. TButton
will not be enough, you have to search for 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将在这种情况下使用。
Registering class ensures that class will be compiled into Delphi application. If class is not used anywhere in code and is not registered, it will not be present in application and extended RTTI will be of any use in that case.
将返回任何类(已注册或未注册),而不使用完全限定类名:
Additional function that will return any class (registered or unregistered) without using fully qualified class name:
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;
这篇关于在Delphi中通过它的名称获取类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!