代码之家  ›  专栏  ›  技术社区  ›  Dsm

没有无参数构造函数的泛型

  •  3
  • Dsm  · 技术社区  · 9 年前

    有人能解释一下为什么在下面的代码中,ClassList会这样做吗 不 要求class1具有无参数构造函数,但class2list 做 要求类2具有无参数构造函数。

    unit Unit11;
    
    interface
    
    uses
      System.Generics.Collections;
    
    type
      class1 = class
      public
        constructor Create( const i : integer ); virtual;
      end;
    
      class1List<T : class1 > = class( TObjectList< T > )
      public
        function AddChild( const i : integer ) : T;
      end;
    
      class2 = class
      public
        constructor Create( const i : integer );
      end;
    
      class2List<T : class2 > = class( TObjectList< T > )
      public
        function AddChild( const i : integer ) : T;
      end;
    
    
    implementation
    
    { class1List<T> }
    
    function class1List<T>.AddChild(const i: integer): T;
    begin
      Result := T.Create( i );
      inherited Add( Result );
    end;
    
    { class2List<T> }
    
    function class2List<T>.AddChild(const i: integer): T;
    begin
      Result := T.Create( i );
      inherited Add( Result );
    end;
    
    { class1 }
    
    constructor class1.Create(const i: integer);
    begin
    
    end;
    
    { class2 }
    
    constructor class2.Create(const i: integer);
    begin
    
    end;
    
    end.
    
    1 回复  |  直到 9 年前
        1
  •  4
  •   David Heffernan    9 年前
    function class1List<T>.AddChild(const i: integer): T;
    begin
      Result := T.Create( i );
      inherited Add( Result );
    end;
    

    的构造函数 class1 已声明 virtual 因此编译器知道 T.Create 生成的实例 T

    Result := T(class1(T).Create( i ));
    

    但编译器的最新版本已经消除了这种欺骗的需要。


    function class2List<T>.AddChild(const i: integer): T;
    begin
      Result := T.Create( i );
      inherited Add( Result );
    end;
    

    的构造函数 class2 不是 事实上的 类别2 ,类可能没有正确初始化。它准备从专用类型调用无参数构造函数 如果存在,则应用 constructor

    现在,您可以应用 建造师 约束,但那没有好处。为了正确初始化实例,需要使用参数调用构造函数。这意味着,实际上,您应该使用第一种方法,使用虚拟构造函数。

    Result := T(class2(T).Create( i ));
    

    但很可能不会做你想做的事。这将调用的静态构造函数 这肯定不是你想要的。