假設有兩個類:
Parent = class
public
procedure virtFunc(); virtual;
procedure other();
end;
Child = class(Parent)
public
procedure virtFunc(); override;
end;
通常,從任何地方virtFunc呼叫Child實體都會呼叫該Child方法的實作。但是,有時呼叫相同級別的實作很有用:
procedure Parent.other();
begin
virtFunc(); // I want to call Parent.virtFunc(), not Child.virtFunc()
end;
我嘗試了什么?
Parent(Self).virtFunc()
(Self as Parent).virtFunc()
顯然,我可以(但這不是問題):
- 以不同的方式重命名它們(childFunc vs parentFunc),
- 洗掉
virtual.
如何在 Delphi 中呼叫方法的當前級別(非多型)版本?
對于那些了解 C 的人,我想要一些等價于Parent::virtFunc()
uj5u.com熱心網友回復:
我認為這樣做的唯一方法是:
Parent.virtFunc通過呼叫中的非虛擬方法來實作Parent。- 當您想以
virtFunc非多型方式呼叫時,您呼叫該非虛擬方法而不是呼叫virtFunc.
uj5u.com熱心網友回復:
一
{
получить доступ к предкам даж если их методы виртуальные
дети выполнятся не будут
пример
TV1 = class
public
A:integer;
function GetH:integer;virtual;
end;
TV2 =class (TV1)
public
B:integer;
function GetH:integer;override;
end;
//////////////////////////////////
function TV2.GetH:integer;
begin
Result:=inherited B;
end;
function TV1.GetH:integer;
begin
Result:=A;
end;
procedure TForm1.Panel1Click(Sender: TObject);
var I:TV2;
s:integer;
begin
I:=TV2.Create;
I.B:=2;
I.A:=1;
//хочу получить доступ с формы к TV1.GetH что бы TV2.GetH не выполнялся
AmVirtual<TV2,TV1>.G(I,
procedure(X2:TV1)
begin
s:=X2.GetH;
end);
showmessage( s.ToString); // >> 1
showmessage( I.GetH.ToString);//>> 3
I.free;
end;
}
type
AmVirtual<T1,T2:class> =class
type
TProc = reference to procedure (X2:T2);
class procedure G(X1:T1;Proc:TProc);static;
end;
class procedure AmVirtual<T1,T2>.G(X1:T1;Proc:TProc);
type
PClass = ^TClass;
var
ClassOld: TClass;
begin
ClassOld := PClass(X1)^;
PClass(X1)^ := T2;
try
proc(X1 as T2);
finally
PClass(X1)^ := ClassOld;
end;
end;
二
type
TProc = procedure (arg:TObject) of object;
var Proc: TProc;
begin
TMethod(Proc).Data:=self;
TMethod(Proc).Code:[email protected];
Proc(Sender);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/518579.html
標籤:德尔福
