Generics constructor with parameter constraint?

后端 未结 5 1021
死守一世寂寞
死守一世寂寞 2020-12-11 02:54
TMyBaseClass=class
  constructor(test:integer);
end;

TMyClass=class(TMyBaseClass);

TClass1=class()
  public
    FItem: T;
    pr         


        
5条回答
  •  甜味超标
    2020-12-11 03:20

    What seems to work in Delphi XE, is to call T.Create first, and then call the class-specific Create as a method afterwards. This is similar to Rudy Velthuis' (deleted) answer, although I don't introduce an overloaded constructor. This method also seems to work correctly if T is of TControl or classes like that, so you could construct visual controls in this fashion.

    I can't test on Delphi 2010.

    type
      TMyBaseClass = class
        FTest: Integer;
        constructor Create(test: integer);
      end;
    
      TMyClass = class(TMyBaseClass);
    
      TClass1 = class
      public
        FItem: T;
        procedure Test;
      end;
    
    constructor TMyBaseClass.Create(test: integer);
    begin
      FTest := Test;
    end;
    
    procedure TClass1.Test;
    begin
      FItem := T.Create; // Allocation + 'dummy' constructor in TObject
      try
        TMyBaseClass(FItem).Create(42); // Call actual constructor as a method
      except
        // Normally this is done automatically when constructor fails
        FItem.Free;
        raise;
      end;
    end;
    
    
    // Calling:
    var
      o: TClass1;
    begin
      o := TClass1.Create();
      o.Test;
      ShowMessageFmt('%d', [o.FItem.FTest]);
    end;
    

提交回复
热议问题