使用RTTI访问严格的私有域 [英] Accesing a strict private field using the RTTI
问题描述
考虑这个简单的代码
{$APPTYPE CONSOLE}
uses
Rtti,
SysUtils;
type
{$M+}
TFoo = class
strict private
class var Field1 : Integer;
field2 : Integer;
private
field3 : Integer;
class var Field4 : Integer;
end;
Var
ctx : TRttiContext;
f : TRttiField;
begin
try
ctx:=TRttiContext.Create;
for f in ctx.GetType(TFoo).GetFields do
Writeln(f.Name);
Writeln('Done');
readln;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
当您运行此操作时,只有 field3
被列出。似乎RTTI不支持 strict private
或 class var
的字段,所以问题是可以使用Rtti或其他方法访问delphi类的严格私有域吗?
并且我阅读了 RTTI.TRttiType.GetFields 方法,但提到这些限制,存在提及这些限制的任何论文或文章?
When you run this, only the field3
is listed. it seems which the RTTI does not support fields which are strict private
or class var
, So the questions are Is possible access a strict private field of a delphi class using Rtti or another method?
and I read the documentation of the RTTI.TRttiType.GetFields method but does mention these restrictions, Exist any paper or article which mentions such limitations?
推荐答案
我现在无法尝试,但您似乎需要的可能是 GetDeclaredFields
而不是 GetFields
。这应该给出一个类的所有(实例)字段,而不是祖先类的字段。如果你也需要这些,你必须递归地继承继承链。
I can't try it right now, but what you seem to need could be GetDeclaredFields
instead of GetFields
. This should give all (instance) fields of a class but not those of an ancestor class. If you need those too, you'll have to recursively go up the inheritance chain.
正如我所说,我现在无法尝试,所以你会必须看看自己是否也可以访问严格的私人领域。
As I said, I can't try it right now, so you'll have to see for yourself if it gives you access to strict private fields as well.
请注意在您的 TFoo 声明中,即使您可能没有打算, Field1和Field2都是类变量。
Note that in your declaration of TFoo, even you probably didn't intend it, both Field1 and Field2 are class variables!.
只需重新格式化您的声明,您将看到我的意思:
Just reformat your declaration, and you'll see what I mean:
TFoo = class
strict private
class var
Field1: Integer;
Field2: Integer;
private
// etc...
> class var 是一个类变量,直到编译器遇到 var , , , >等等,请尝试这样做,您还将看到正在写的 Field2 :
Everything that comes after class var is a class variable, until the compiler encounters var, strict, private, protected, etc. Try this, and you'll also see Field2 being written:
TFoo = class
strict private
class var
Field1: Integer;
var
Field2: Integer;
// etc...
或者尝试:
TFoo = class
strict private
Field2: Integer;
class var
Field1: Integer;
// etc...
这意味着 GetFields和GetDeclaredFields不会在严格的私人领域有任何问题。他们只是不返回类变量。这是有道理的,海事组织。类变量不是被调查对象的成员。
This means that GetFields and GetDeclaredFields don't have any problems with strict private fields. They just don't return class variables. That makes sense, IMO. Class variables are not members of the object being investigated.
这篇关于使用RTTI访问严格的私有域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!