【发布时间】:2013-12-04 17:37:06
【问题描述】:
在一个文件中,我有一个带有 ID 属性的基类:
type
TBase = class
private
class function GetID(ACombo: TCombo): Integer; virtual;
class procedure SetID(ACombo: TCombo; AValue: Integer); virtual;
public
class property ID[ACombo: TCombo]: Integer read GetID write SetID;
end;
在第二个文件中,我有另一个类,从 TBase 下降。出于偶然、无知或其他原因,创建了一个与现有属性/字段同名的新属性/字段。
type
TSubBase = class(TBase)
private
class function GetID(ACombo: TCombo): Integer; override;
class procedure SetID(ACombo: TCombo; AValue: Integer); override;
end;
并在接下来的方式中使用这些类:
TBaseClass = class of TBase;
function Base(): TBaseClass;
implementation
var
BaseInstance: TBaseClass;
function Base(): TBaseClass;
begin
if not Assigned(BaseInstance) then
begin
if SOME_PARAM then
BaseInstance:= TBase
else
BaseInstance:= TSubBase;
end;
Result := BaseInstance;
end;
if Base.StationCode[cmbStation] = SOME_VALUE then
但是我在编译时遇到了错误:
[DCC Error] uMyFile.pas(69): E2355 Class property accessor must be a class field or class static method
我也一直在尝试使用静态关键字...并根据下面同事的建议找到了一些解决方法。
type
TBase = class
private
class function GetIDStatic(ACombo: TCombo): Integer; static;
class procedure SetIDStatic(ACombo: TCombo; AValue: Integer); static;
class function GetID(ACombo: TCombo): Integer; virtual; abstract;
class procedure SetID(ACombo: TCombo; AValue: Integer); virtual; abstract;
public
class property ID[ACombo: TCombo]: Integer read GetIDStatic write SetIDStatic;
end;
TSubBase = class(TBase)
private
class function GetID(ACombo: TCombo): Integer; override;
class procedure SetID(ACombo: TCombo; AValue: Integer); override;
end;
TBaseClass = class of TBase;
function Base(): TBaseClass;
implementation
var
BaseInstance: TBaseClass;
function Base(): TBaseClass;
begin
if not Assigned(BaseInstance) then
begin
if SOME_PARAM then
BaseInstance:= TBase
else
BaseInstance:= TSubBase;
end;
Result := BaseInstance;
end;
class function TBase.GetIDStatic(ACombo: TCombo): Integer; static;
begin
Result := BaseInstance.GetID(ACombo);
// Or maybe below ?
// Result := Base().GetID(ACombo);
end;
class procedure TBase.SetIDStatic(ACombo: TCombo; AValue: Integer); static;
begin
BaseInstance.SetID(ACombo, AValue);
// Or maybe below ?
// Base().SetID(ACombo, AValue);
end;
但在最后一个变体中 - 实现是丑陋的,我同意大卫关于使用类属性和简单重构的方法的“梦想”,如下所述:
class properties ID[ACombo: TCombo]: Integer ....
=>>
class function GetID(ACombo: TCombo): Integer; virtual;
class pocedure SetID(ACombo: TCombo; AValue: Integer); virtual;
感谢大家在这里挖掘的乐趣!
【问题讨论】:
-
是的,确实不需要重复。我修改了示例
-
你还在苦苦挣扎吗?
-
非常感谢大卫!是的,我找到了一些解决方法......但这很棘手,而且对我来说不包括方法
-
你明白类属性是在编译时绑定的吗?从对问题的编辑和您的接受来看,您似乎还没有完全理解这一点。我想帮助你,但你似乎一心想要让类属性做他们不能做的事情。您最新编辑中的代码非常骇人听闻。并且可以使用虚拟类方法轻松解决。然后没有破解,代码看起来很干净。没有卑鄙的全局变量。你能告诉我你不明白我回答的哪一部分吗?
-
大卫,我确实了解财产,但我不会弯腰。我只有一个限制,我无法重构生产代码。我自己不能接受这样的解决方案,无论如何都必须向我的上级询问重构这些类!
标签: delphi oop properties