Delphi: 我如何知道哪个索引 属性 具有使用 RTTI 的字符串索引
Delphi: How can I know which of the indexed property has the string index using 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(东京)
您应该可以使用读取方法参数。像这样:
readingMethod := IndexedProperty.ReadMethod;
readMethodParameters := readingMethod.GetParameters;
if readMethodParameters[0].ParamType.TypeKind = tkUString then
// We have the string version
您显然应该检查 readMethod 是否已分配以及参数数量是否大于零等。
来自雷米:
在这种情况下,字符串类型是 tkUString (UnicodeString),并且自 Delphi 2009 年以来一直如此。
基于如下代码:
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(东京)
您应该可以使用读取方法参数。像这样:
readingMethod := IndexedProperty.ReadMethod;
readMethodParameters := readingMethod.GetParameters;
if readMethodParameters[0].ParamType.TypeKind = tkUString then
// We have the string version
您显然应该检查 readMethod 是否已分配以及参数数量是否大于零等。
来自雷米:
在这种情况下,字符串类型是 tkUString (UnicodeString),并且自 Delphi 2009 年以来一直如此。