-1

This function should convert a solution given at: eval fields of a record into a reuseable function. Actually this code below does not compile and I have no idea how to get it functional ...

procedure EnumerateFieldandValues(const m: TObject; RecordParams: TStringList);
var
  i: Integer;
  rtype: TRTTIType;
  fields: TArray<TRttiField>;
begin
  rtype := TRttiContext.Create.GetType(TypeInfo(TObject.ClassType));
  // Memo1.Lines.Add(rtype.ToString);
  fields := rtype.GetFields;
  for i := 0 to High(fields) do
    RecordParams.Add(Format('%s: %s :: %s', [fields[i].Name,
      fields[i].FieldType.ToString, fields[i].GetValue(@m).ToString]));

end;
Community
  • 1
  • 1
user1769184
  • 1,571
  • 1
  • 19
  • 44
  • When you say "does not compile", you should also include the compiler error (and indicate the line that causes it in the code). Please [edit] to do so. You have that information right in front of you, so there's absolutely no reason not to provide it to us as well. – Ken White May 23 '14 at 18:00
  • 2
    not `TypeInfo(TObject.ClassType)`, but `TypeInfo(m.ClassType)` – Igor May 23 '14 at 18:05
  • m.classtype give other error : [DCC Fehler] Unit_rttiValues.pas(162): E2133 Standardfunktion TYPEINFO erwartet einen Typbezeichner – user1769184 May 23 '14 at 18:31
  • You don't discuss in that thread - why? – MBo May 23 '14 at 18:48
  • @Igor, if you want the type info of an object, you can just ask for it directly: `m.ClassInfo`. `TypeInfo` is a compiler-magic function that requires a type identifier, not a class reference. It's evaluated at compile time, so if the code compiles at all, it will give you the type info of the `ClassType` method, which is simply `TClass`. – Rob Kennedy May 23 '14 at 18:50
  • Why are you trying to adapt the record code from one answer in that question when there's already an object version in another answer? – Rob Kennedy May 23 '14 at 18:50
  • want to make a universal function, where I can pass different records or class for dumping content of fields and field names; previous answer is only valid for a given record type. – user1769184 May 23 '14 at 20:28

1 Answers1

1

You are making several mistakes in your code. Try this instead:

procedure EnumerateFieldAndValues(m: TObject; RecordParams: TStrings);
var
  rtype: TRttiType;
  field: TRttiField;
begin
  rtype := TRttiContext.Create.GetType(m.ClassType);
  // Memo1.Lines.Add(rtype.ToString);
  for field in rtype.GetFields do
    RecordParams.Add(Format('%s: %s :: %s', [field.Name, field.FieldType.ToString, field.GetValue(m).ToString]));
end;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770