如何在Delphi XE中通过其名称获取类类型引用? [英] How to get the class type reference by its name in Delphi XE?

查看:267
本文介绍了如何在Delphi XE中通过其名称获取类类型引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际上是试图使用Rtti来暗示一个泛型方法的调用者。它应该这样工作:




  • 我将提供类名,方法名称和参数

  • 调用者将通过调用此类的指定方法来执行其工作



所以我需要类引用才能得到它Rtti信息,并寻求我想要调用的方法。



有没有办法做到这一点,没有实现我想要使用的类的类引用列表?

解决方案

要使用他的名字获取类的引用,您必须使用 TRttiContext.FindType 函数传递类的名称,并使用< a href =http://docwiki.embarcadero.com/VCL/XE2/en/RTTI.TRttiType.AsInstance> AsInstance 属性,然后你可以调用类的构造函数。

  var 
实例: TRttiInstanceType;
ctx:TRttiContext;
mClass:TValue;
begin
ctx:= TRttiContext.Create;
实例:= ctx.FindType(ClassName).AsInstance; // ClassName类似于'Classes.TStringList';
mClass:= Instance.GetMethod('Create')。Invoke(Instance.MetaclassType,[]);

//在这里做你的东西


end;


I'm actually trying to use Rtti to implent a generic method invoker. It should work like this:

  • I'll provide the class name, method name, and arguments
  • the invoker will do its work by invoking the specified method of this class

So I need the class reference in order to get its Rtti information and seek for the method I want to invoke.

Is there any way to do that without implementing a class reference list of the classes I want to be working with?

解决方案

To get the class reference using his name you must use the TRttiContext.FindType function passing the Name of the class and the retrieve the instance using the AsInstance property and then you can call the constructor of the class.

var
  Instance : TRttiInstanceType;
  ctx : TRttiContext;
  mClass : TValue;
begin
  ctx := TRttiContext.Create;   
  Instance := ctx.FindType(ClassName).AsInstance; //ClassName is something like  'Classes.TStringList';
  mClass := Instance.GetMethod('Create').Invoke(Instance.MetaclassType,[]);

   //do your stuff here


end;

这篇关于如何在Delphi XE中通过其名称获取类类型引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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