请原谅以下代码示例的冗长。使用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;
请忽略这个“设计”的明显缺陷。我想访问属性IndxProp的RTTI,因此将IndxProp移动到了published部分。令人失望的是,索引属性不允许在published部分中使用。据我所知(请参见Barry Kelly在How do I access Delphi Array Properties using RTTI的评论),转向D2010也不能实现这一点。
另一方面,以下是Robert Loves的博客中的一句话:“...属性和方法现在可以通过RTTI在public和published部分中使用,并且字段在所有部分中都可用。”(我斜体)。
我的问题是:如果确实可以在D2010中获取公共字段的RTTI,那么我的原始示例(如上所示)应该在D2010中(使用RTTI)工作吗?提前感谢您!
TRttiIndexedProperty
,它提供了获取索引属性的运行时类型信息的功能。 - menjaraz