加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – 如何在类构造函数中访问RTTI?

发布时间:2020-12-15 04:11:21 所属栏目:大数据 来源:网络整理
导读:不允许使用此代码: class constructor TOmniMultiPipelineStage.Create;var RTTIType: TRttiType;begin RTTIType:= TRttiContext.GetType(self);end; [dcc32 Error] OtlParallel.pas(5040): E2003 Undeclared identifier: ‘self’ 该变体也是不允许的: cl
不允许使用此代码:
class constructor TOmniMultiPipelineStage.Create;
var
  RTTIType: TRttiType;
begin
  RTTIType:= TRttiContext.GetType(self);
end;

[dcc32 Error] OtlParallel.pas(5040): E2003 Undeclared identifier: ‘self’

该变体也是不允许的:

class constructor TOmniMultiPipelineStage.Create;
var
  RTTIType: TRttiType;
begin
  //Not really what I want because I want the actual type of the class
  //Not a fixed ancestor type 
  RTTIType:= TRttiContext.GetType(TOmniMultiPipelineStage);
end;

[dcc32 Error] OtlParallel.pas(5039): E2076 This form of method call only allowed for class methods or constructor

如何在类构造函数中获取类的RTTI信息?

自我注意:循环遍历类的所有后代:Delphi: At runtime find classes that descend from a given base class?

解决方法

使用TObject的 ClassInfo类方法:
class constructor TMyClass.ClassCreate;
var
  ctx: TRttiContext;
  typ: TRttiType;
begin
  typ := ctx.GetType(ClassInfo);
end;

请注意,我还修改了对GetType的调用语法,这是一个实例方法,因此必须在TRttiContext的实例上调用.

对你来说更大的问题是类构造函数不会对你有用.类构造函数是静态的.它们仅针对定义它们的类型执行一次.正如您所期望的那样,它们不会在派生类的上下文中执行.

同样对于班级变量,你在评论中讨论.只有一个类var的单个实例.您期望并希望每个派生类都有新的实例.

因此,虽然ClassInfo回答了您提出的问题,但它对您没有任何实际用处.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读