列出实现接口的类的所有属性 [英] List all the properties from a class that implements an interface

查看:177
本文介绍了列出实现接口的类的所有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,它有一个接口:

I have a class that has an interface on it:

TInterface = interface(IXMLNode)
  function Get_One: Boolean;
  function Get_Two: Boolean;
  function Get_Three: Boolean;
  procedure Set_One(Value: Boolean);
  procedure Set_Two(Value: Boolean);
  procedure Set_Three(Value: Boolean);
  property One: Boolean read Get_One write Set_One;
  property Two: Boolean read Get_Two write Set_Two;
  property Three: Boolean read Get_Three write Set_Three;
end;

TTesting = class(TXMLNode, TInterface)
protected
  function Get_One: Boolean;
  function Get_Two: Boolean;
  function Get_Three: Boolean;
  procedure Set_One(Value: Boolean);
  procedure Set_Two(Value: Boolean);
  procedure Set_Three(Value: Boolean);
end;

并希望列出所有属性。我试过这个:

And would like to list all the properties. I tried this:

GetMem(PropList, SizeOf(PropList^));

PropCount := GetPropList(TTesting.ClassInfo, tkAny, nil);   
GetMem(PropList, PropCount*SizeOf(PPropInfo));
GetPropList(TTesting.ClassInfo, tkAny, PropList);

PropList 始终为空。当我用任何形式尝试时,不是这样。任何想法?

And PropList is always empty. Not so when I tried with any form. Any idea ?

推荐答案

GetPropList() RTTI只描述被声明为的类属性和类方法(您的项目都不是),只有在类或祖先(如 TPeristent )已被标记为 {$ M +}

GetPropList() is based on old-style RTTI that only describes class properties and class methods which are declared as published (which none of your items are) and only if the class, or an ancestor (like TPeristent), has been marked as {$M+}.

您正在使用XE2,可以使用扩展RTTI(Delphi 2010中介绍)。它没有这样的限制。例如:

Since you are using XE2, you can use Extended RTTI (which was introduced in Delphi 2010) instead. It does not have such limitations. For example:

uses
  System.Rtti;

var
  Ctx: TRttiContext;
  PropList: TArray<TRttiProperty>;
begin
  PropList := Ctx.GetType(TTesting).GetProperties;
  ...
end;

更新:界面是一种特殊情况。一个接口只允许包含抽象方法,属性只是语法糖来调用这些方法。因此,在接口上定义的属性不是真正的属性,就像它们在类类型上一样,因此不会生成RTTI。这就是为什么你不能枚举从接口继承的属性。您可以使用扩展RTTI枚举界面的方法,但只有当界面已标记为 {$ M +}

Update: interfaces are a special case. An interface is only allowed to contain abstract methods, properties are just syntax sugar to call those methods. So properties defined on an interface are not real properties, like they are on class types, and thus do not generate RTTI. That is why you cannot enumerate properties that are inherited from an interface. You can enumerate the interface's methods using Extended RTTI, but only if the interface has been marked with {$M+}.

这篇关于列出实现接口的类的所有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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