class function如何知道所在的类

ReinhardCao 2010-02-23 12:03:12
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它,来实现,但每个子类都要实现一次,太麻烦了,有否更好的方法?
...全文
157 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
ReinhardCao 2010-02-23
  • 打赏
  • 举报
回复
呵呵,原来类方法也有self,受教了!
Harryfin 2010-02-23
  • 打赏
  • 举报
回复
楼上的写法是错的,Self.Create根本就没有创建实例,刚好ClassName也是类方法,所以才没出错。
budded 2010-02-23
  • 打赏
  • 举报
回复

class function TParent.GetInstance: TParent;
begin
Result := Self.Create; // 就这么着
end;

procedure TForm1.Button1Click(Sender: TObject);
var
FObj: TParent;
begin
FObj := TChild.GetInstance;
ShowMessage(FObj.ClassName);
end;
Harryfin 2010-02-23
  • 打赏
  • 举报
回复

class function TParent.GetInstance:TParent;
begin
result := TParentClass(FindClass(Self.ClassName)).Create;
end;

initialization
RegisterClass(TParent);
RegisterClass(TChild);

16,748

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 语言基础/算法/系统设计
社区管理员
  • 语言基础/算法/系统设计社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧