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

delphi – 如何从父类调用子类构造函数?

发布时间:2020-12-15 09:51:45 所属栏目:大数据 来源:网络整理
导读:有没有办法从父类调用子类的创建?下面是这个Duplicate方法,我希望调用子类的构造函数,以便底部的测试成功. type IBlaT = interface(IInvokable) ['{34E812BF-D021-422A-A051-A492F25534C4}'] function GetIntFromIface(): Integer; function Duplicate(): I
有没有办法从父类调用子类的创建?下面是这个Duplicate方法,我希望调用子类的构造函数,以便底部的测试成功.

type

  IBla<T> = interface(IInvokable)
    ['{34E812BF-D021-422A-A051-A492F25534C4}']
    function GetIntFromIface(): Integer;
    function Duplicate(): IBla<T>;
  end;

  TClassA<T> = class(TInterfacedObject,IBla<T>)
  protected
    function GetInt(): Integer; virtual;
  public
    function GetIntFromIface(): Integer;
    function Duplicate(): IBla<T>;
  end;

  TClassB = class(TClassA<Integer>,IBla<Integer>)
  protected
    function GetInt(): Integer; override;
  end;

function TClassA<T>.Duplicate: IBla<T>;
begin
  Exit(TClassA<T>.Create());
end;

function TClassA<T>.GetInt: Integer;
begin
  Exit(1);
end;

function TClassA<T>.GetIntFromIface: Integer;
begin
  Exit(GetInt());
end;

function TClassB.GetInt: Integer;
begin
  Exit(2);
end;

procedure TestRandomStuff.Test123;
var
  o1,o2: IBla<Integer>;
begin
  o1 := TClassB.Create();
  o2 := o1.Duplicate();    
  Assert.AreEqual(o2.GetIntFromIface,2);
end;

解决方法

您可以使用RTTI执行此操作:

uses
  System.Rtti;

....

function TClassA<T>.Duplicate: IBla<T>;
var
  ctx: TRttiContext;
  typ: TRttiType;
  mthd: TRttiMethod;
  inst: TValue;
begin
  typ := ctx.GetType(ClassInfo);
  mthd := typ.GetMethod('Create');
  inst := mthd.Invoke((typ as TRttiInstanceType).MetaclassType,[]);
  inst.AsObject.GetInterface(IBla<T>,Result);
end;

很可能有一种更简洁的方法来使用RTTI来调用构造函数(我对Delphi中的RTTI几乎一无所知),所以你可以很好地阅读该主题而不是将上述内容作为规范的方法来实现.

当然,这假设所有子类都使用TObject中定义的无参数构造函数.这可能是相当有限的.如果您发现自己不得不以更基本的方式重新思考设计,我不会感到惊讶.

如果你的子类都没有实现构造函数,那么你可以使它更简单,而根本不使用RTTI:

function TClassA<T>.Duplicate: IBla<T>;
begin
  ClassType.Create.GetInterface(IBla<T>,Result);
end;

但请注意,这会调用TObject中定义的构造函数,并且不会调用子类中定义的任何构造函数.

(编辑:李大同)

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

    推荐文章
      热点阅读