Recent

Author Topic: A Case for Generics or something else?  (Read 1621 times)

Zvoni

  • Hero Member
  • *****
  • Posts: 2315
A Case for Generics or something else?
« on: March 17, 2019, 12:05:27 am »
Hi Folks,

let's suppose i have a class like this.
Code: Pascal  [Select][+][-]
  1. TMyClass = Class
  2. Private
  3.    FString:String;
  4.    FInteger:Integer;
  5. Protected
  6.    //Some Fields, Functions, Procedures
  7. Public
  8.   Constructor Create;
  9.   Destructor Destroy;Override;
  10.  

And i want to add one more Field of unknown ClassTpe
How would i go about it?
From Visual Basic i just had to implement an Interface, and i could assign it
Something like:
(I'm trying to speak Visual Basic in Pascal-Syntax!)
Code: Pascal  [Select][+][-]
  1. TInterFaceClass=Class
  2.  
  3. TRealClass1=class (Implements TInterFaceClass) //-->This is not Inheritance!!!
  4. TRealClass2=class (Implements TInterFaceClass)
  5. //some more classes, which are completely different from each other except they implement that Interface
  6. //In VB i could do something like this
  7. TSomeClass=Class
  8. Private
  9.   FClass:TInterFaceClass;
  10. Public
  11.   Property AClass:TInterFaceClass Read FClass Write FClass;
  12.  
  13. //Later in code:
  14. SC:TSomeClass;
  15. RC1:TRealClass1;
  16. RC2:TRealClass2;
  17. //Create the class etc.
  18. SC.AClass:=RC1;
  19. //DoSomething
  20. SC.AClass:=RC2;
  21.  

Possible?
I found this, which looks close as it gets to what i look for:
Code: Pascal  [Select][+][-]
  1. type
  2.   TGenericClass<T> = class
  3.     Field: T;
  4.     AString:String;
  5.     AInteger:Integer;
  6.     procedure Method(A: T);
  7.     Procedure DoSomething(AValue:Boolean);
  8.     Function GetSomething:String;
  9.     function Foo: T;
  10.     property Bar: T read Foo write Method;
  11.   end;
  12.  
  13. function TGenericClass<T>.Foo: T;
  14. begin
  15.   Result := Field;
  16. end;
  17.  
  18. procedure TGenericClass<T>.Method(A: T);
  19. begin
  20.   Field:=A;
  21. end;
  22.  
« Last Edit: March 17, 2019, 12:10:59 am by Zvoni »
One System to rule them all, One Code to find them,
One IDE to bring them all, and to the Framework bind them,
in the Land of Redmond, where the Windows lie
---------------------------------------------------------------------
Code is like a joke: If you have to explain it, it's bad

JuhaManninen

  • Global Moderator
  • Hero Member
  • *****
  • Posts: 4459
  • I like bugs.
Re: A Case for Generics or something else?
« Reply #1 on: March 17, 2019, 02:09:49 am »
Interfaces and generics are 2 different things.
Object Pascal has interfaces, too. Use them to match the logic of your VB code.
Mostly Lazarus trunk and FPC 3.2 on Manjaro Linux 64-bit.

 

TinyPortal © 2005-2018