问题描述
我想实例化一个类,但我只有一个字符串的名称.有办法吗?
I'd like to instantiate a class but I only have its name in a string. Is there a way?
推荐答案
这来自 Delphi 帮助(Delphi 2006,但至少也可从 Delphi 7 获得):
This is from Delphi help (Delphi 2006, but also available from at least Delphi 7):
语法function GetClass(const AClassName: string): TPersistentClass;
Syntaxfunction GetClass(const AClassName: string): TPersistentClass;
说明调用 GetClass 从类名中获取类.此类可用作需要类的例程的参数.在 GetClass 找到它之前,必须先注册 Class.在表单声明(实例变量)中引用的表单类和组件类在表单加载时自动注册.其他类可以通过调用 RegisterClass 或 RegisterClasses 进行注册.
DescriptionCall GetClass to obtain a class from a class name. This class can be used as a parameter to routines that require a class. The Class must be registered before GetClass can find it. Form classes and component classes that are referenced in a form declaration (instance variables) are automatically registered when the form is loaded. Other classes can be registered by calling RegisterClass or RegisterClasses .
这里有一些示例代码.之所以如此有效,只是因为 TButton 是一个 TControl,因此类型转换是有效的.
Here some sample code. Works as such only because TButton is a TControl and therefore the typecast is valid.
procedure TForm1.FormCreate(Sender: TObject);
begin
RegisterClasses([TButton, TForm]);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
CRef : TPersistentClass;
AControl : TControl;
begin
CRef := GetClass('TButton');
if CRef<>nil then
begin
AControl := TControl(TControlClass(CRef).Create(Self));
with AControl do
begin
Parent := Self;
Width := 50;
Height := 30;
end;
end;
end;
这篇关于有没有办法在delphi中按名称实例化一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!