Delphi:如何使用RTTI知道哪个索引属性具有字符串索引

3

基于以下类似的代码:

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(东京版)。
1个回答

4
您应该能够使用read方法的参数。可以像这样操作:
readingMethod := IndexedProperty.ReadMethod;
readMethodParameters := readingMethod.GetParameters;
if readMethodParameters[0].ParamType.TypeKind = tkUString then
  // We have the string version

显然,您需要检查readMethod是否被赋值以及参数数量是否大于零等。

来自Remy:

在这种情况下,字符串类型是tkUString(UnicodeString),从Delphi 2009开始就是这样。


5
D2009+标准中的string类型是UnicodeString,因此在这个例子中,TypeKind将会是tkUStringtkString代表ShortStringtkLString代表AnsiStringtkWString代表WideString)。 - Remy Lebeau

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接