链接到原始问题是否可以获得类属性的索引?并由 Remy Lebeau 和 RRUZ 回答
program Demo;
{$APPTYPE CONSOLE}
uses
System.SysUtils, Winapi.Windows,
System.Rtti, System.TypInfo;
type
TMyClass = class
private
function GetInteger(const Index: Integer): Integer;
procedure SetInteger(const Index, Value: Integer);
public
property P1: Integer Index 1 read GetInteger write SetInteger;
property P2: Integer Index 2 read GetInteger write SetInteger;
property P3: Integer Index 3 read GetInteger write SetInteger;
end;
{ TMyClass }
function TMyClass.GetInteger(const Index: Integer): Integer;
begin
Result := Index;
end;
procedure TMyClass.SetInteger(const Index, Value: Integer);
begin
//
end;
{------------------------------------------------------------------------------}
function GetPropertyIndex(const AClass: TClass; APropertyName: string): Integer;
var
Ctx: TRttiContext;
begin
Ctx := TRttiContext.Create;
Result := (Ctx.GetType(AClass).GetProperty(APropertyName) as TRttiInstanceProperty).Index;
end;
{------------------------------------------------------------------------------}
var
C: Cardinal;
I: Integer;
N: Integer;
begin
try
C := GetTickCount;
for N := 1 to 1000000 do
I := GetPropertyIndex(TMyClass, 'P2');
WriteLn(GetTickCount - C, ' ms - The index of the property P2 is ', I);
ReadLn;
except
on E: Exception do Writeln(E.ClassName, ': ', E.Message);
end;
end.
在我的电脑上,这个测试大约需要 5 秒。但是当我TRttiContext
在调用之前使用GetPropertyIndex()
- 例如
...
begin
try
TRttiContext.Create.Free;
C := GetTickCount;
for N := 1 to 1000000 do
I := GetPropertyIndex(TMyClass, 'P2');
...
相同的测试只需要 ~ 1 秒。为什么 ?
编辑我在测试第二个示例时发现的问题
...
var
Ctx: TRttiContext;
C: Cardinal;
I: Integer;
N: Integer;
begin
try
C := GetTickCount;
for N := 1 to 1000000 do
begin
Ctx := TRttiContext.Create;
I := (Ctx.GetType(TMyClass).GetProperty('P2') as TRttiInstanceProperty).Index;
end;
WriteLn(GetTickCount - C, ' ms - The index of the property P2 is ', I);
ReadLn;
except
on E: Exception do Writeln(E.ClassName, ': ', E.Message);
end;
end.
但原因在第二次测试中更明显,问题也是如此。