我需要创建类似的东西,我用 PHP 语言实现。
假设我创建了一个定义 2 个静态成员变量的基类,然后子类应该能够“覆盖”它们,所以如果我在 BaseClass 中定义了静态变量“someStatic”,然后我子类化为 DerivedClass,当我调用 TDerivedOne.someStatic,程序应该显示派生类的 someStatic.. 但 Delphi 不是这种情况,我肯定是错误地实现了它..
目前,我实现了另一种设计方法,其中变量没有声明为静态,然后创建了一个名为'setup'的虚拟抽象方法,然后这个setup会在BaseClass构造函数上调用,但是这个设计需要创建的对象首先在我们可以检索所需的变量之前。
现在出于好奇,我想知道是否可以实现虚拟静态变量来节省“几次打字……”
这是问题的代码片段
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils;
type
TBaseClass = class
protected
class var someStatic: string;
public
class function get: string; virtual;
end;
TDerived = class( TBaseClass )
(*
//if i uncomment this section, then the print bellow will print the Base's static var
protected
class var someStatic: string;
*)
end;
TDerived2 = class( TBaseClass )
end;
class function TBaseClass.get: string;
begin
Result := someStatic;
end;
begin
// ------If the class is defined per unit, this one should be on the initialization section
TBaseClass.someStatic := 'base';
TDerived.someStatic := 'derived';
TDerived2.someStatic := 'derived2';
// ------END OF INITIALIZATION
try
//i'm expecting this would print 'derived' but it prints 'derived2' :'(
//i am using DelphiXE
//apparently delphi treat the statics differently from that of php's
writeln( TDerived.get );
readln;
except
on E: Exception do
writeln( E.ClassName, ': ', E.Message );
end;
end.
干杯:)