Frage

I have a boolean field which I want to set using MyField.SetValue(Self, MyValue). No matter what I tried, I keep getting typecast errors.

The problem is that MyValue always contains an ordinal and is not recognized as containing a boolean. I know that boolean is an enumeration, which is an ordinal, but it should still be possible to set boolean fields and properties using TValue.

I tried the following to initiate MyValue but every time MyValue.IsOrdinal = True while MyValue.IsBoolean = False:

  1. MyValue := TValue.From(True);
  2. MyValue := TValue.From<Boolean>(True);
  3. MyBool := True; MyValue := MyValue.From(MyBool);
  4. MyBool := True; MyValue := MyValue.From<Boolean>(MyBool);
  5. MyValue := True;
  6. MyBool := True; MyValue := MyBool;
  7. MyBool := True; TValue.Make(@MyBool, TypeInfo(Boolean), MyValue);

Is there a way to get the TValue to accept that it contains a boolean i.s.o. an ordinal so that MyField.SetValue(Self, MyValue) will succeed?

Thanks in advance,

Decolaman

War es hilfreich?

Lösung

The TValue works fine with boolean values.

Check this sample code

{$APPTYPE CONSOLE}

uses
  Rtti,
  SysUtils;

Type
  TAnyClass=class
   AField : Boolean;
  end;

Var
 Ctx       : TRttiContext;
 MyValue   : TValue;
 A         : TAnyClass;
 MyField   : TRttiField;
begin
  try
    Ctx:=TRttiContext.Create;
    A:=TAnyClass.Create;
    try
      MyField:=Ctx.GetType(TAnyClass).GetField('AField');

      MyValue:= MyValue.From(False);
      MyField.SetValue(A, MyValue);
      Writeln('The Value of AField Is '+BoolToStr(A.AField, True));

      MyValue:= MyValue.From(True);
      MyField.SetValue(A, MyValue);
      Writeln('The Value of AField Is '+BoolToStr(A.AField, True));
    finally
      A.Free;
      Ctx.Free;
    end;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top