Delphi-从字符串创建类 [英] Delphi - Create class from a string

查看:91
本文介绍了Delphi-从字符串创建类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码

name := 'Foo';
If name = 'Foo' then
  result := TFoo.Create
else if name = 'Bar' then 
  result := TBar.Create
else if name = 'FooFoo' then
  result := TFooFoo.Create;

有没有办法做

result := $name.create

还是某种基于变量值创建类的方法?

or some way of creating class based of a variable value?

所有类都扩展了相同的基类.

All the classes extended the same base class.

推荐答案

从Delphi 2010开始,增强的RTTI允许您执行此操作,而无需创建自己的类注册表.

Starting with Delphi 2010, the enhanced RTTI allows you do this without having to creating your own Class Registry.

使用RTTI单元,您可以使用几个选项.

Using the RTTI Unit you have several options available.

对于参数较少的构造方法,最简单的方法之一是.

For Parameter Less Constructors one of the easiest is.

var
 C : TRttiContext;
 O : TObject;
begin
  O := (C.FindType('UnitName.TClassName') as TRttiInstanceType).MetaClassType.Create;
  ...
 end;

以下是使用TRttiMethod.Invoke()

var
 C : TRttiContext;
 T : TRttiInstanceType;
 V : TValue;

begin
  T := (C.FindType('StdCtrls.TButton') as TRttiInstanceType);
  V := T.GetMethod('Create').Invoke(T.metaClassType,[self]);
  (V.AsObject as TWinControl).Parent := self;
end;

我写了 RTTI单元上有几篇文章,因为有很多可用的选项.

I wrote several articles on the RTTI unit as there is many options available.

已更新基于David的请求:

Updated Based on David Request:

比较使用类类型(虚拟构造函数)和TRttiType.Invoke

Comparing the usage of construction using the Class Type (Virtual Constructor) with the TRttiType.Invoke

  • 在所有版本的Delphi中均可使用
  • 产生更快的代码
  • 要求在编译时了解祖先.
  • 要求类注册表通过字符串名称(如RRUZ所述)查找类
  • 仅在Delphi 2010或更高版本中可用.
  • 较慢的代码
  • 实现考虑名称冲突的类注册表
  • 在编译时需要祖先知识.
  • Only works in Delphi 2010 or later.
  • Slower code
  • Implements a Class Registry that takes Name conflicts into account
  • Requires NO knowledge of ancestry at compile time.

我个人发现每种服务都有不同的用途.如果我预先知道所有类型,则可以使用类类型方法".

I personally find each serves a different purpose. If I know all the types up front the I use the Class Type Method.

这篇关于Delphi-从字符串创建类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆