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 |1 Answer
Reset to default 3The 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
版权声明:本文标题:oop - Different property types in derived classes - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744682436a2619492.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
TClassAInfo
andTClassBInfo
from common base class and then use that class type for defining theinfo
property type in yourTClassA
andTClassB
. – SilverWarior Commented Mar 14 at 8:07TClassAInfo
andTClassBInfo
from a common base class is indeed an option. Another option, ifTClassAInfo
andTClassBInfo
really have nothing in common, is to simply use different properties:InfoA
andInfoB
. That would be correct., if it's completely different things. – Matthias B Commented Mar 14 at 14:03