Delphi通用类可以从其类参数中下降吗? [英] Can a Delphi generic class descend from its class argument?
问题描述
TSingleton< RealClass,InheritsFrom:class> = class(InheritsFrom)
strict private
class var FInstance:RealClass;
protected
procedure InstanceInitialization; virtual;
public
析构函数Destroy;覆盖
类程序创建;重新引入
类函数实例:RealClass;
类程序InstanceFree;
结束
目标是能够将单例模式插入在继承树中。所以不要这样声明:
TMySingletonComponent = class(TComponent)
end;
需要在那里实现单例模式,我会声明如下:
TMyGenericSingletonComponent = class(TSingleton< TMyGenericSingletonComponent,TComponent>)
end;
可惜,这不行。我收到以下错误(D2010):
TSingleton< RealClass,InheritsFrom:class> = class(InheritsFrom)/// E2021需要类类型
现在我在想,德尔福XE?有没有一些干净的黑客可以用来在D2010做这项工作?有没有一些根本原因,为什么这不能工作?
根据设计,你不能创建一个派生的泛型类从其中一个类型的参数。
I've been trying to define a generic, inheritable TSingleton class. Here's what I had in progress:
TSingleton<RealClass, InheritsFrom : class> = class(InheritsFrom)
strict private
class var FInstance : RealClass;
protected
procedure InstanceInitialization;virtual;
public
destructor Destroy; override;
class procedure Create; reintroduce;
class function Instance : RealClass;
class procedure InstanceFree;
end;
The goal was to be able to "insert" the singleton pattern in an inheritance tree. so instead of declaring something like this :
TMySingletonComponent = class(TComponent)
end;
And need to implement the singleton pattern there, I would declare something like this :
TMyGenericSingletonComponent = class(TSingleton<TMyGenericSingletonComponent,TComponent>)
end;
Sadly, this won't work. I'm getting the following error(In D2010):
TSingleton<RealClass, InheritsFrom : class> = class(InheritsFrom) ///E2021 Class type required
Now I was wondering, would this work in Delphi XE? Is there some "clean hack" I could use to make this work in D2010? Is there some fundamental reasons why this can't work?
By design, you can't create a generic class which derives from one of its type arguments.
这篇关于Delphi通用类可以从其类参数中下降吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!