【问题标题】:Polymorphism in Delphi GenericsDelphi泛型中的多态性
【发布时间】:2010-05-14 17:52:54
【问题描述】:
type 
  TParent=class
    public
      member1:Integer;
  end;

  TChild=class(TParent)
  public
    member2:Integer;
  end;


  TGArray<T: TParent>=class
    public
      function test:T;
    end;

  implementation

  var g:TGArray<TChild>;

    function TGArray<T>.test:T;
    begin
      Result:=??.create; // <<<<  Problem !
    end;


  begin
    g := TGArray<TChild>.Create;
    g.test.member2 := 1234;
  end.

g.test 必须返回该类的一个实例。我尝试了多种方法:

1.  Result := Result.create; //Exception
2.  Result := TChildClass.Create; //Error
3.  type TGArray<T: class> = class; //and above 2. The same errors/exceptions.

这样做的目的是创建一个通用的类数组。数组存储在泛型类中并返回实例,但是如何?

如果我完成这件事,我会缩短我的代码 3 倍,但我做不到。请提出任何解决方案。

【问题讨论】:

    标签: delphi generics delphi-2009 delphi-2010 generic-programming


    【解决方案1】:

    你没有说 #2 中的错误是什么,但我敢打赌它会告诉你requires a constructor constraint. 添加一个,它应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-05
      • 2011-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-11
      • 2017-03-28
      • 2014-06-01
      相关资源
      最近更新 更多