【问题标题】:how to access protected class method如何访问受保护的类方法
【发布时间】:2017-02-05 23:40:21
【问题描述】:

我们有这个基类:

TCustomContextOpenGL = class(TContext3D)
  protected
    **class** procedure CreateSharedContext; virtual; abstract;
  end;

并在程序中知道我们所做的当前上下文类:

TContextManager.DefaultContextClass => return TContextClass = class of TContext3D;

这将例如返回 TCustomAndroidContext 或 TCustomContextIOS 覆盖 CreateSharedContext 但让它受到保护

我的问题是我需要做的

TContextManager.DefaultContextClass.CreateSharedContext 

但这当然行不通,因为 CreateSharedContext 在 TCustomContextOpenGL 中受到保护 :( 我该怎么办?

【问题讨论】:

  • @AndreiGalatyn 不太一样,因为我在这里说的是类而不是对象:(
  • 这看起来更像 C++ 而不是 Delphi。在回答您的问题时,您不能将其保留为受保护并访问它 - 这就是受保护的目的!因此,不要让它受到保护,而是将覆盖公开。基类仍然不能直接访问,但子类可以。
  • 你不能用RegisterContextClassesUnRegisterContextClasses
  • 是的,我可以,但是对于我想要做的单行代码使用 registerContextClasses / UnRegisterContextClasses 看起来过于复杂:( 最后我最终使用 {$ifdef android} ....{$否则 ifdef ios}....

标签: delphi firemonkey


【解决方案1】:

最好的办法是避免直接调用受保护的方法。如果它是第 3 方类并且您无法更改它,那么您可以像访问任何其他受保护类成员一样访问受保护类方法。

有一个示例如何访问受保护的对象事件: Accessing protected event of TWinControl

访问受保护类方法的类似方式:

type
  TCustomContextOpenGLHack = class(TCustomContextOpenGL);
  CCustomContextOpenGLHack = class of TCustomContextOpenGLHack;

procedure Test;
begin
  CCustomContextOpenGLHack(TContextManager.DefaultContextClass).CreateSharedContext;
end;

【讨论】:

  • 这是行不通的,因为 TContextManager.DefaultContextClass 返回的不是对象而是类(即:TContext3D 的类):(
  • @andray: 啊,就这么简单吗? :) 好的,谢谢!
猜你喜欢
  • 2020-07-26
  • 2013-04-06
  • 2017-12-09
  • 2018-04-20
  • 2014-05-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-02
  • 1970-01-01
相关资源
最近更新 更多