class function如何知道所在的类

ReinhardCao ReinhardCao 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
TParent类有个GetInstance的类函数,如何使在TParent中调用时创建TParent对象,如果是在子类TChild中调用,就用返回TChild对象。
TParent=class
protected
constructor Create;virtual;
public
class function GetInstance:TParent;
end;

TParentClass=class of TParent;

TChild=class(TParent)
protected
constructor Create;override;
end;

class function TParent.GetInstance:TParent;
var
c:TParentClass;
begin
c:=当前的类;//如果在对象方法中,可以这样写 c:=TParentClass(self.ClassType),但是在类方法中就不行了
result:=c.create;
end;

调用:
var
parent:TParent;
child:TChild;
begin
parent:=TParent.GetInstance;
child:=TChild(TChild.GetInstance);
end;

目前的实现方法是将GetInstance定义为virtual,TChild中override它,来实现,但每个子类都要实现一次,太麻烦了,有否更好的方法?
...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部