Delphi – 从字符串创建类
发布时间:2020-12-15 10:15:04 所属栏目:大数据 来源:网络整理
导读:我有这样的代码 name := 'Foo';If name = 'Foo' then result := TFoo.Createelse if name = 'Bar' then result := TBar.Createelse if name = 'FooFoo' then result := TFooFoo.Create; 有办法吗 result := $name.create 还是以某种方式创建基于变量值的类?
我有这样的代码
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 还是以某种方式创建基于变量值的类? 所有的类都扩展了相同的基类。 解决方法
从Delphi 2010开始,增强的RTTI允许您执行此操作,而无需创建自己的类注册表。
使用RTTI单元,您有几个选项可用。 对于参数较少的构造函数,最简单的一个是。 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单元上写了several articles,因为有很多选项可用。 根据大卫要求更新: 使用类型(虚拟构造函数)与TRttiType.Invoke进行比较 类类型方法:(虚拟构造函数) >在所有版本的Delphi中工作 TRttiType.Invoke()方法 >仅适用于Delphi 2010或更高版本。 我个人觉得每个都有不同的目的。如果我知道前面的所有类型,我使用类类型方法。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |