不允许使用此代码:
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
自我注意:循环遍历类的所有后代: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回答了您提出的问题,但它对您没有任何实际用处.