英文:
How to conditionally change class inheritance at compile-time in Delphi??
问题
我正在处理一个Delphi项目,其中我定义了一组特定的类,例如:
TClassA = class(TObject)
...
TClassB = class(TObject)
...
TMyClass = class(TClassA)
...
我有一个要求,根据在编译时确定的某些条件,我希望TMyClass实际上从TClassB继承。
基本上,我想能够像这样编写:
{$IFDEF SOME_COMPILE_TIME_CONDITION}
TMyClass = class(TClassB)
{$ELSE}
TMyClass = class(TClassA)
{$ENDIF}
在Delphi中是否有可能在编译时有条件地定义TMyClass的父类?如果可以,我该如何实现?如果不行,您有什么解决方法或替代方法可以建议吗?
英文:
I'm working on a Delphi project where I have a specific set of classes defined, such as:
TClassA = class(TObject)
...
TClassB = class(TObject)
...
TMyClass = class(TClassA)
...
I have a requirement where, based on certain conditions that are determined at compile time, I want TMyClass to instead inherit from TClassB.
Essentially, I would like to be able to write something like this:
{$IFDEF SOME_COMPILE_TIME_CONDITION}
TMyClass = class(TClassB)
{$ELSE}
TMyClass = class(TClassA)
{$ENDIF}
Is it possible in Delphi to conditionally define the parent class of TMyClass at compile time? If so, how can I achieve this? If not, are there any workarounds or alternative approaches you can suggest?
答案1
得分: 2
我不确定这是否符合更加优雅的标准,但无论如何,你可能会难以找到其他任何东西:
{$IFDEF SOME_COMPILE_TIME_CONDITION}
TMyParentClass = TClassB
{$ELSE}
TMyParentClass = TClassA
{$ENDIF}
TMyClass = class(TMyParentClass)
英文:
I'm not sure if this qualifies for more elegant, but you might have difficulties to find anything else anyway:
{$IFDEF SOME_COMPILE_TIME_CONDITION}
TMyParentClass = TClassB
{$ELSE}
TMyParentClass = TClassA
{$ENDIF}
TMyClass = class(TMyParentClass)
答案2
得分: 2
这可能会有点偏离,具体取决于您要做什么,但根据我所了解的信息,我会使用接口来解决这个问题。
伪代码...
type
TMyClass = class(TMyBaseClass);
TMyBaseClass = class
private
fImplementation: IMyImplementation;
public
constructor Create;
end;
constructor TMyBaseClass.Create;
begin
{$ifdef CONDA}
fImplementation := TCondAImplementation.Create;
{$else}
fImplementation := TCondBImplementation.Create;
{$end}
end;
然后您的派生类可以调用基类的受保护方法,这些方法会调用不同的实现,或者直接提供对 fImplementation
成员的受保护访问。
英文:
This might be a little off, depending on what you're trying to do, but based on the information I have I'd solve this problem using an interface.
pseudocode...
type
TMyClass = class( TMyBaseClass );
TMyBaseClass = class
private
fImplementation: IMyImplementation;
public
constructor Create;
end;
constructor TMyBaseClass.Create;
begin
{$ifdef CONDA}
fImplementation := TCondAImplementation.Create;
{$else}
fImplementation := TCondBImplementation.Create;
{$end}
end;
Your descendant can then either call protected methods of the base class which call on the differing implementations, OR provide protected access to the fImplementation member directly.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论