How to hide a protected procedure of an object?

痞子三分冷 提交于 2019-12-22 05:12:08

问题


In one base class, there's a protected procedure. When inheriting that class, I want to hide that procedure from being used from the outside. I tried overriding it from within the private and even strict private sections, but it can still be called from the outside. The Original class is not mine, so I can't change how TOriginal is defined.

Is it possible to hide this procedure in my inherited class? And how?

type
  TOriginal = class(TObject)
  protected
    procedure SomeProc;
  end;

  TNew = class(TOriginal)
  strict private
    procedure SomeProc; override;
  end;

回答1:


Protected methods are already hidden from the outside. (Mostly; see below.) You cannot reduce the visibility of a class member. If the base class declared the method protected, then all descendants of that class may use the method.


In Delphi, other code within the same unit as a class may access that class's protected members, even code from unrelated classes. That can be useful sometimes, but usually to work around other design deficiencies. If you have something that's "really, really" supposed to be protected, you can make it strict protected, and then the special same-unit access rule doesn't apply.




回答2:


Once exposed you can not hide it but you can do this to spot where it is called in limit way

TOriginalClass = class
public
  procedure Foo;
end;

TNewClass = class(TOriginalClass) 
public
  procedure Foo; reintroduce;
end;

implementation

procedure TNewClass.Foo;
begin
  Assert(False, 'Do not call Foo from this class');
  inherited Foo;
end;

var Obj: TNewClass;
Obj := TNewClass.Create;
Obj.Foo; // get assert message

Will not get Assert error if declared as TOriginalClass
var Obj: TOriginalClass;
Obj := TNewClass.Create;
Obj.Foo; // Never get the assert message


来源:https://stackoverflow.com/questions/9400170/how-to-hide-a-protected-procedure-of-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!