将类字符串转换为 TClass
鉴于课程: 用途 调用注册表; //其中定义了 TRemotable。
类型 TMyLabel = 类(TRemotable) //一些已发布的道具 TMySubLabel = 类(TMyLabel) //更多已发布的道具
//some other classes descendent of TMyLabel.
TMyLabelClass = class of TMyLabel;
我的要求是实现:
function StringToClass(string aClassName): TClass;
begin
//your implementation goes here
end;
用法:
function GetMyLabelInstance(string aClassName):TMyLabel;
var
lCloned: TMyLabel;
begin
Tclass lClass = StringToClass('TMySubLabel');
lCloned := TMyLabelClass(lClass).Create;
end;
我使用的是 Delphi 7 并且我的对象不是从 TPersistent 派生的,因此此解决方案不适用于我的情况: 如何将类名作为字符串转换为类?
谢谢,
Given the Classes:
uses
InvokeRegistry; //where TRemotable is defined.
type
TMyLabel = class(TRemotable)
//some published props
TMySubLabel = class(TMyLabel)
//more published props
//some other classes descendent of TMyLabel.
TMyLabelClass = class of TMyLabel;
My requirement is to implement:
function StringToClass(string aClassName): TClass;
begin
//your implementation goes here
end;
Usage:
function GetMyLabelInstance(string aClassName):TMyLabel;
var
lCloned: TMyLabel;
begin
Tclass lClass = StringToClass('TMySubLabel');
lCloned := TMyLabelClass(lClass).Create;
end;
I am using Delphi 7 and my objects are not derived from TPersistent, thus this solution is not applicable for my case:
How to convert classname as string to a class?
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您的类不是
TPercient
后代,因此您必须实现自己的RegisterClass
/FindClass
过程。我通常通过在
TStringList
(或TDictionary
对于较新的 Delphi 版本)中注册类及其名称来实现此目的,如 TOndrej 的回答。我在定义类的单元的初始化部分中进行注册。然后,您可以使用 FindClass 函数根据类的名称检索该类,或者直接使用工厂过程根据类的名称创建正确类的实例。
我还认为将 TStringList、注册过程和工厂过程打包在一个作为单例实现的类中是一种很好的做法。
如果您想用作工厂,您还必须向基类 (TMyLabel) 添加虚拟构造函数,并定义元类类型
TMyLabelClass = TMyLabel 的类
,并强制转换 StringList.Objects[i ] 到 TMyLabelClass 而不是 TClassAs your classes are not
TPersistent
descendants, you have to implement your ownRegisterClass
/FindClass
procedures.I usually do this by registering the classes with their names in a
TStringList
(orTDictionary<string, TClass>
for newer Delphi versions), as in TOndrej's answer. I do the registration in theinitialization
section of the unit in which the class is defined.Then you can have a
FindClass
function to retrieve the class based on his name, or directly a factory procedure which creates an instance, of the right class based on the name of the class.I also consider a good practice to pack up the
TStringList
, the registration procedure and the factory procedure in one class implemented as a singleton.If you want to use as a factory you also have to add a virtual constructor to the base class (TMyLabel), and define a metaclass type
TMyLabelClass = class of TMyLabel
, and cast the StringList.Objects[i] to TMyLabelClass instead of TClass