【问题标题】:Delphi: RTTI for indexed properties in 2010?Delphi:2010 年索引属性的 RTTI?
【发布时间】:2011-01-30 06:47:59
【问题描述】:

请原谅以下代码示例的冗长。使用 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 移至已发布部分。令我失望的是,我发现已发布部分中不允许索引属性。据我了解(请参阅 How do I access Delphi Array Properties using RTTI 上的 Barry Kellys 评论),迁移到 D2010 不会让我这样做。

另一方面,以下是来自Robert Loves blog 的引用:“...属性和方法现在可以通过 RTTI 在公共和已发布部分中使用,并且字段在所有部分中都可用。” (我的斜体。)

我的问题是:如果确实可以在 D2010 中为公共字段获取 RTTI,那么我的原始示例(如上所示)不应该在 D2010(使用 RTTI)中工作吗?提前致谢!

【问题讨论】:

    标签: delphi delphi-2010 rtti


    【解决方案1】:

    是的,如果属性读取器所做的只是索引到数组字段或列表类字段,那么您可以使用 RTTI 直接索引到该字段。但是,这有点脆弱,因为它破坏了您的封装,要求您将代码编写到特定的实现细节而不是一般原则,而这是 RTTI 的主要优点。您的 RTTI 代码必须与您的类的确切结构相匹配,如果它发生变化,您也必须更改代码。这有点违背了使用 RTTI 的目的。

    但是,如果没有其他可用的方法,因为数组属性没有 RTTI,至少目前可能是唯一的方法。

    编辑:更新此答案。 XE2 中的扩展 RTTI 系统添加了对索引属性的支持。 (但是,由于不相关的稳定性问题,您可能需要等待 XE3...)

    【讨论】:

    • 更新:Delphi XE2 引入了TRttiIndexedProperty,它提供了获取索引属性的运行时类型信息的功能。
    猜你喜欢
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多