简体   繁体   English

为什么我不能声明通用形式

[英]why i can't declare a generic form

what im trying to do is basically declare a form like this: 我试图做的基本上是声明这样的形式:

TFormCRUDBase<T : class> = class(TFormLayoutBase, MVP.Intf.CRUD.ICRUDView<T>)
{ ... }
end;

the compiler doesn't accuse any error or warning messages if this feature is allowed or not, anyway but when i try to add some controls in the designer i get this message 无论如何,编译器不会指责任何错误或警告消息,但是无论如何,但是当我尝试在设计器中添加一些控件时,我会收到此消息

Declaration of class TFormCRUDBase is missing or incorrect.

so the question is why the syntax allow me to use and the IDE simply kicks me away. 所以问题是为什么语法允许我使用,而IDE却让我无所适从。

thx in advance 提前

Simply put, the form designer does not support generic types. 简而言之,表单设计器不支持泛型类型。

The compiler is fine with generic types. 编译器可以使用泛型类型。 You can build the UI, add controls etc. with run time code. 您可以使用运行时代码来构建UI,添加控件等。 But the form designer does not support generic types. 但是表单设计器不支持泛型。

You asked for a work arround. 您要求工作安排。 The solurion are simple, yet not elegant. 解决方案很简单,但并不优雅。 You have to make at strong type class, and make you form inhirited from that. 您必须制作强类型类,并从中吸取形式。

First I make some dummy types: 首先,我创建一些虚拟类型:

type
  ICRUDView<T> = Interface
   function GetObject : T;
  end;

  TMyObject = class
    function Time: String;
  end;

and a Simple implementation: 和一个简单的实现:

{ TMyObject }

function TMyObject.Time: String;
begin
  Result := TimeToStr(now);
end;

procedure TForm5.FormCreate(Sender: TObject);
begin
  Caption := Self.GetObject.Time;
end;

Then the strong type from which you have to inherited from: 然后是您必须从中继承的强类型:

type
  TMyClassForm = class(TForm, ICRUDView<TMyObject>)
  strict private
    InternalObject: TMyObject;
  public
    function GetObject: TMyObject;
  end;

and its implementation: 及其实现:

{ TMyClassForm }

function TMyClassForm.GetObject: TMyObject;
begin
  if (InternalObject = nil) then
    InternalObject := TMyObject.Create;

  Result := InternalObject;
end;

At last you make your form inhirited from your newly created class: 最后,使您的表单从新创建的类中汲取灵感:

  TForm5 = class(TMyClassForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

and use it in your form 并以您的形式使用

procedure TForm5.FormCreate(Sender: TObject);
begin
  Caption := Self.GetObject.Time;
end;

It's working but its not elegant ! 它正在工作,但并不优雅!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM