admin管理员组

文章数量:1389872

I have a problem with building my classes. I did a lot of inheritance and stuff, but I just can't get my mind wrapped around this problem.

This is what I'd like to achieve:

TClassAInfo=class
 public
  Function GetInfo:String;
end;

TClassA=Class(TBase)
private
 FInfo:TClassAInfo
public
 property Info:TClassAInfo read FInfo;
end;

TClassBInfo=class(TClassAInfo)
  //Does something different then ClassAInfo
end;

TClassB=Class(TClassA)
private
 FInfo:TClassBInfo
public
 property Info:TClassBInfo read FInfo;
end;

So, I can always call x.Info no matter what type x is, but always get the correct Info type.

Is this possible in Delphi 12?

I have a problem with building my classes. I did a lot of inheritance and stuff, but I just can't get my mind wrapped around this problem.

This is what I'd like to achieve:

TClassAInfo=class
 public
  Function GetInfo:String;
end;

TClassA=Class(TBase)
private
 FInfo:TClassAInfo
public
 property Info:TClassAInfo read FInfo;
end;

TClassBInfo=class(TClassAInfo)
  //Does something different then ClassAInfo
end;

TClassB=Class(TClassA)
private
 FInfo:TClassBInfo
public
 property Info:TClassBInfo read FInfo;
end;

So, I can always call x.Info no matter what type x is, but always get the correct Info type.

Is this possible in Delphi 12?

Share Improve this question edited Mar 13 at 23:22 Remy Lebeau 601k36 gold badges507 silver badges851 bronze badges asked Mar 13 at 22:12 Wolfgang BuresWolfgang Bures 7277 silver badges22 bronze badges 3
  • You could derive both TClassAInfo and TClassBInfo from common base class and then use that class type for defining the info property type in your TClassA and TClassB. – SilverWarior Commented Mar 14 at 8:07
  • This is called the strategy design pattern, btw – DelphiCoder Commented Mar 14 at 9:40
  • Deriving TClassAInfo and TClassBInfo from a common base class is indeed an option. Another option, if TClassAInfo and TClassBInfo really have nothing in common, is to simply use different properties: InfoA and InfoB. That would be correct., if it's completely different things. – Matthias B Commented Mar 14 at 14:03
Add a comment  | 

1 Answer 1

Reset to default 3

The type of x.Info depends on the type of x, and TClassA.Info and TClassB.Info are separate and not related to each other, so your can't switch between them with a single type of x.

One way (the only way?) to get the kind of behavior you want is if x is typed as a user-specified parameter of a Generic function, eg:

type
  TSomeClass = class
  public
   procedure DoSomething<T: class>(x: T);
  end;

procedure TSomeClass.DoSomething<T>(x: T);
begin
  // type of x.Info depends on type of T
end;

本文标签: oopDifferent property types in derived classesStack Overflow