请原谅以下代码示例的冗长。使用 Delphi 2009,我创建了两个类 TOtherClass 和 TMyClass:
TOtherClass = class(TObject)
public
FData: string;
end;
TMyClass = class(TObject)
private
FIndxPropList: Array of TOtherClass;
function GetIndxProp(Index: Integer): TOtherClass;
procedure SetIndxProp(Index: Integer; Value: TOtherClass);
public
property IndxProp[Index: Integer]: TOtherClass read GetIndxProp write SetIndxProp;
end;
访问说明符实现为
function TMyClass.GetIndxProp(Index: Integer): TOtherClass;
begin
Result := self.FIndxPropList[Index];
end;
procedure TMyClass.SetIndxProp(Index: Integer; Value: TOtherClass);
begin
SetLength(self.FIndxPropList, Length(self.FIndxPropList) + 1);
self.FIndxPropList[Length(self.FIndxPropList) - 1] := Value;
end;
它的使用可以说明如下:
procedure Test();
var
MyClass: TMyClass;
begin
MyClass := TMyClass.Create;
MyClass.IndxProp[0] := TOtherClass.Create;
MyClass.IndxProp[0].FData := 'First instance.';
MyClass.IndxProp[1] := TOtherClass.Create;
MyClass.IndxProp[1].FData := 'Second instance.';
MessageDlg(MyClass.IndxProp[0].FData, mtInformation, [mbOk], 0);
MessageDlg(MyClass.IndxProp[1].FData, mtInformation, [mbOk], 0);
MyClass.IndxProp[0].Free;
MyClass.IndxProp[1].Free;
MyClass.Free;
end;
别介意这种“设计”的明显缺陷。我意识到我希望能够通过 RTTI 访问属性 IndxProp,随后将 IndxProp 移至已发布部分。令我失望的是,我发现已发布部分中不允许索引属性。据我了解(请参阅 Barry Kellys 在How do I access Delphi Array Properties using RTTI上的评论),迁移到 D2010 不会让我这样做。
另一方面,以下引自Robert Loves 博客:“...属性和方法现在可通过 RTTI 在公共部分和已发布部分中使用,并且字段在所有部分中都可用。” (我的斜体。)
我的问题是:如果确实可以在 D2010 中为公共字段获取 RTTI,那么我的原始示例(如上所示)不应该在 D2010(使用 RTTI)中工作吗?提前致谢!