由于包含类型名称的文本字符串,是有一些方法来获得相应的类型本身?

我希望做这样的事情:

type
  TSomeType<T> = class
    // yadda yadda
  end;

procedure DoSomething;
var
  obj : TObject;
begin
  o := TSomeType<GetTypeByName('integer')>.Create;
  // do stuff with obj
end;

我在几个RTTI解释在网上看了,看着通过德尔福单位并没有看到什么我要找的。这是可能的?

有帮助吗?

解决方案

没有,泛型是完全编译时。

其他提示

在2010年的Delphi新RTTI单元具有在检索单元的接口部分声明类型的一种方式。对于任何给定类型,由TRttiType实例表示,该TRttiType.QualifiedName属性返回可与TRttiContext.FindType以后可以用于检索类型的名称。限定名称为全单元名(包括命名空间,如果存在的话),接着是“”,后跟完整的类型名称(包括外类型的,如果它嵌套的)。

因此,可以与TRttiType检索整数类型的表示(在context.FindType('System.Integer')的形式)。

但是该机制不能用于检索未在编译时实例化的一般类型的实例;实例在运行时需要的运行时代码生成。

您可以随时注册类型为某种注册表(由字符串列表或字典管理),并创建一个工厂函数,然后返回适当的对象。不幸的是,你必须提前知道什么类型的,你会要。一些类似的Delphi功能的RegisterClass和findClass的(在类单元)。我的想法是直接把通用模板类型到列表中。

可能的使用的一个示例:

RegisterCustomType('Integer',TSomeType<Integer>);
RegisterCustomType('String',TSomeType<String>);

if FindCustomType('Integer') <> nil then
  O := FindCustomType('Integer').Create;

编辑:下面是一个使用tDictionary从Generics.Collections处理注册表存储特定的简单的实现......我将离开提取到有用的方法是一个简单的练习为读者这一点。

var
  o : TObject;
begin
  TypeDict := TDictionary<String,TClass>.Create;
  TypeDict.Add('integer',TList<integer>);
  if TypeDict.ContainsKey('integer') then
    o := TypeDict.Items['integer'].Create;
  if Assigned(o) then
    ShowMessage(o.ClassName);
end;

另一个编辑:我在此些心思让昨晚,并且发现了另一种技术,它可以合并到这个概念。接口。这里是一个快速什么也不做的例子,但可以很容易地被扩展:

TYPE
  ITest = interface
    ['{0DD03794-6713-47A0-BBE5-58F4719F494E}']
  end;

  TIntfList<t> = class(TList<T>,ITest)
  public
    function QueryInterface(const IID: TGUID; out Obj): HRESULT; stdcall;
    function _AddRef: Integer; stdcall;
    function _Release: Integer; stdcall;
  end;

procedure TForm1.Button7Click(Sender: TObject);
var
  o : TObject;
  fTestIntf : ITest;
begin
  TypeDict := TDictionary<String,TClass>.Create;
  TypeDict.Add('integer',TIntfList<integer>);
  if TypeDict.ContainsKey('integer') then
    o := TypeDict.Items['integer'].Create;
  if Assigned(o) and Supports(o,ITest,fTestIntf) then
    ShowMessage(o.ClassName);
end;

当然,你将不得不执行的QueryInterface,_AddRef和_Release方法和扩展接口做更有用的东西。

如果您忘记了仿制药和基本类型,即“的RegisterClass”功能将是有益的。但它并不适用于仿制药或基本类型的工作。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top