存储通用类型参数以备将来使用
Storing generic type parameter for future usage
我有几个 TRootFrame 的 TFrames。我通过带有通用参数的方法显示这些帧,例如:
class
..
procedure Push<T:TFrameRoot>;
end.
Implementation
procedure TFormMain.Push<T>(const closeMenu: Boolean);
begin
ShowFrame<T>();
if closeMenu then
DoCloseMenu();
end;
这一切都很好,现在我想推送堆栈上显示的帧,以便稍后弹出它,如:
procedure TFormMain.Push<T>(const closeMenu: Boolean);
begin
fFrameStack.Push(T);
ShowFrame<T>();
if closeMenu then
DoCloseMenu();
end;
procedure TFormMain.Pop<T>();
var
frameType:T;
begin
frameType := fFrameStack.Pop();
ShowFrame<frameType as T>();
end;
你有什么想法吗?
谢谢,爱德华
将ShowFrame<T:TFrameRoot>
更改为ShowFrame(frameClass: TFrameRootClass)
并声明TFrameRootClass = class of TFrameRoot
。
因为您的 T
被限制为 TFrameRoot
,您可以简单地将 T
分配给 TFrameRootClass
variable/parameter 的变量。另外 fFrameStack
是 Stack<TFrameRootClass>
procedure TFormMain.ShowFrame(frameRootClass: TFrameRootClass);
begin
end;
procedure TFormMain.Push<T>(const closeMenu: Boolean);
begin
fFrameStack.Push(T);
ShowFrame(T);
end;
procedure TFormMain.Pop<T>();
var
frameType: TFrameRootClass;
begin
frameType := fFrameStack.Pop();
ShowFrame(frameType);
end;
个人建议:如果您将泛型类型参数限制为某些 class 无论如何,拥有泛型通常毫无意义,而是使用 class 引用(即 class of ...
东西)。
您可以轻松地让 Push
和 Pop
方法仅采用 TFrameRootClass
.
的参数
我有几个 TRootFrame 的 TFrames。我通过带有通用参数的方法显示这些帧,例如:
class
..
procedure Push<T:TFrameRoot>;
end.
Implementation
procedure TFormMain.Push<T>(const closeMenu: Boolean);
begin
ShowFrame<T>();
if closeMenu then
DoCloseMenu();
end;
这一切都很好,现在我想推送堆栈上显示的帧,以便稍后弹出它,如:
procedure TFormMain.Push<T>(const closeMenu: Boolean);
begin
fFrameStack.Push(T);
ShowFrame<T>();
if closeMenu then
DoCloseMenu();
end;
procedure TFormMain.Pop<T>();
var
frameType:T;
begin
frameType := fFrameStack.Pop();
ShowFrame<frameType as T>();
end;
你有什么想法吗?
谢谢,爱德华
将ShowFrame<T:TFrameRoot>
更改为ShowFrame(frameClass: TFrameRootClass)
并声明TFrameRootClass = class of TFrameRoot
。
因为您的 T
被限制为 TFrameRoot
,您可以简单地将 T
分配给 TFrameRootClass
variable/parameter 的变量。另外 fFrameStack
是 Stack<TFrameRootClass>
procedure TFormMain.ShowFrame(frameRootClass: TFrameRootClass);
begin
end;
procedure TFormMain.Push<T>(const closeMenu: Boolean);
begin
fFrameStack.Push(T);
ShowFrame(T);
end;
procedure TFormMain.Pop<T>();
var
frameType: TFrameRootClass;
begin
frameType := fFrameStack.Pop();
ShowFrame(frameType);
end;
个人建议:如果您将泛型类型参数限制为某些 class 无论如何,拥有泛型通常毫无意义,而是使用 class 引用(即 class of ...
东西)。
您可以轻松地让 Push
和 Pop
方法仅采用 TFrameRootClass
.