问题
I got some problems with RTTi .. i wana to enumerate all constans values in Record type
type TMyRecord = record
const
value1: Integer=10;
value2: Integer=13;
value3: Integer=18;
value4: Integer=22;
end;
procedure TForm3.Button1Click(Sender: TObject);
var
ctx:TRttiContext ;
Field:rtti.TRttiField ;
begin
for Field in ctx.GetType(TypeInfo(TMyRecord)).GetFields do
ListBox1.Items.Add(Field.Name ); // i got nothing
end;
but when my Record is not a const , my code work fine
type TMyRecord = record
value1: Integer;
value2: Integer;
value3: Integer;
value4: Integer;
end;
procedure TForm3.Button1Click(Sender: TObject);
var
ctx:TRttiContext ;
Field:rtti.TRttiField ;
begin
for Field in ctx.GetType(TypeInfo(TMyRecord)).GetFields do
ListBox1.Items.Add(Field.Name ); //its work
end;
回答1:
RTTI cannot enumerate constants. Whilst they might appear to be fields, they are not. They are implemented just like any other constant, inside the record's namespace.
You may have to consider an alternative approach. For example you could use attributes instead of constants. Or perhaps adding a class function that enumerates these constants.
Yet another approach would be like this:
type
TMyRecord = record
value1: Integer;
value2: Integer;
value3: Integer;
value4: Integer;
end;
const
MyConst: TMyRecord = (
value1: 10;
value2: 13;
value3: 18;
value4: 22
);
来源:https://stackoverflow.com/questions/13096120/enum-const-record-fields