Enum Const Record Fields

天涯浪子 提交于 2019-12-11 02:56:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!