首页 > 解决方案 > Delphi:我如何知道哪个索引属性具有使用 RTTI 的字符串索引

问题描述

基于如下代码:

TListWrapper = class
  strict private
    FList: TStringList;
    function GetItem(index: Integer): TObject; overload;
    function GetItem(index: string): TObject; overload;
  public
    property Items[index: Integer]: TObject read GetItem; default;
    property Items[index: string]: TObject read GetItem; default;
end;

我想编写一段代码,使用 RTTI 获取字符串索引属性的值。像这样的东西:

var
  MyList: TListWrapper;
  InstanceType: TRttiInstanceType;
  IndexedProperty: TRttiIndexedProperty;

begin
  MyList:=TListWrapper.Create;

  LContext:=TRttiContext.Create;
  InstanceType:=LContext.GetType(MyList.ClassType) as TRttiInstanceType;
  for IndexedProperty in InstanceType.GetIndexedProperties do
    if IndexedProperty.Name.ToLower = 'items' then
    begin
      //There are two indexed properties with name 'items'
    end;
  LContext.Free;
  MyList.Free;
end;

问题:我怎样才能知道哪个索引属性具有字符串索引,以便我可以得到这样的值?

IndexedProperty.GetValue(MyList, ['some_string_index']);

注意:我使用的是 Delphi 10.2.3(东京)

标签: delphirtti

解决方案


您应该能够使用读取方法参数。像这样的东西:

readingMethod := IndexedProperty.ReadMethod;
readMethodParameters := readingMethod.GetParameters;
if readMethodParameters[0].ParamType.TypeKind = tkUString then
  // We have the string version

您显然应该检查 readMethod 是否已分配以及参数的数量是否大于零等。

来自雷米:

在本例中,字符串类型为 tkUString (UnicodeString),自 Delphi 2009 以来一直如此。


推荐阅读