class function如何知道所在的类
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它,来实现,但每个子类都要实现一次,太麻烦了,有否更好的方法?