繁体   English   中英

存储泛型类型参数以备将来使用

[英]Storing generic type parameter for future usage

我有一些从 TRootFrame 派生的 TFrame。 我通过带有通用参数的方法显示这些帧,例如:

    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变量/参数的变量。 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 of ...东西)。

您可以轻松地使您的PushPop方法简单地采用TFrameRootClass的参数。

暂无
暂无

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

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