Delphi通用类可以从其类参数中下降吗? [英] Can a Delphi generic class descend from its class argument?

查看:288
本文介绍了Delphi通用类可以从其类参数中下降吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试定义一个通用的,可继承的TSingleton类。这是我正在进行的:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆