N
N
ndbn2016-09-20 12:44:12
Delphi
ndbn, 2016-09-20 12:44:12

How to assign a boolean expression to a TObject field?

There is a class with a field type TObject.
The field value can be a boolean type or another class.
It is not possible to assign a boolean value to it, type conversions (explicit or as TObject) do not help.
Is it possible to do this at all, maybe it's worth somehow making your own TBoolean ?!

TBar = class
    field : TObject;
  end;
... 
var 
  bar : TBar;
...  
  bar.field := True;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mercury13, 2016-09-20
@ndbn

I'll try to guess the problem. There is a certain field (let's call it UserData), but we have boolean user data!
Solution 1: Direct conversion regardless of type incompatibilities.

someObj.UserData := TObject(true);
someBool := boolean(someObj.UserData);

+ Most efficient of all.
− It is forbidden to dereference.
Solution 2: Create some DummyObject. Designate nil=false, <>nil = true.
someObj.UserData := dummyObject;
someBool := (someObj.UserData <> nil);

initialization
  dummyObject := TObject.Create;
finalization
  dummyObject.Free;
end.

+ Effective enough, can be dereferenced.
− If the class has a non-disabled auto-destruction of UserData - a bummer!
Solution 3: Create a TBoolObject class.
TBoolObject = class
public
  Value : boolean;
  // конструкторы опущу, деструктор не нужен
end.

someObj.UserData := TBoolObject(true);
someBool := (someObj.UserData as TBoolObject).Value;

+ Works when the class has UserData auto-destruction.
- Otherwise, the sheepskin is not worth the candle, then we will have to destroy these objects ourselves.
If you have memory savings here and you need to keep an object or boolean in the same memory, solution 4 works.
TObjBool = record
case integer of
0 : ( asObj : TObject );
1 : ( asBool : boolean );
end;

+ Very efficient.
- The programmer himself must keep track of what is there: an object or a boolean.

K
kalapanga, 2016-09-20
@kalapanga

Some kind of perversion was invented. Of course it can't be.
And how it is necessary, without knowing the task, no one will tell you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question