Of course, this piece of code will not compile. First I need to cast a TObject value to Integer. Then, read it as a string. What function should I use?
for i := 1 to 9 do begin
cmbLanguage.Items.AddObject(Format('Item %d', [i]), TObject(i));
end;
cmbLanguage.ItemIndex := 2;
ShowMessage(cmbLanguage.Items.Objects[cmbLanguage.ItemIndex]);
Or maybe it's possible to use String instead of Integer in the first place?
Can JavaScript object property be a number? Against what many think, JavaScript object keys cannot be Number, Boolean, Null, or Undefined type values. Object keys can only be strings, and even though a developer can use other data types to set an object key, JavaScript automatically converts keys to a string a value.
If your object is a String , then you can use the Integer. valueOf() method to convert it into a simple int : int i = Integer. valueOf((String) object);
Use Integer constructor to convert int primitive type to Integer object.
cmbLanguage.Items.AddObject(Format('Item %d', [i]), TObject(i));
Here you are adding an item with an "object" which is actually an integer (i
) casted to a TObject
.
Since you are actually storing an int in the object field, you can just cast it back to Integer, then convert that to a string:
ShowMessage(IntToStr(Integer(cmbLanguage.Items.Objects[cmbLanguage.ItemIndex])));
Note that you are not really converting anything here, you're just pretending that your integer is a TObject so the compiler doesn't complain.
If you know you will be using Delphi-7 for the rest of your life stick with the TObject(i) cast. Otherwise start using proper objects, this will save you headaches when upgrading to 64 bit.
Unit uSimpleObjects;
Interface
type
TIntObj = class
private
FI: Integer;
public
property I: Integer Read FI;
constructor Create(IValue: Integer);
end;
type
TDateTimeObject = class(TObject)
private
FDT: TDateTime;
public
property DT: TDateTime Read FDT;
constructor Create(DTValue: TDateTime);
end;
Implementation
{ TIntObj }
constructor TIntObj.Create(IValue: Integer);
begin
Inherited Create;
FI := IValue;
end;
{ TDateTimeObject }
constructor TDateTimeObject.Create(DTValue: TDateTime);
begin
Inherited Create;
FDT := DTValue;
end;
end.
Usage:
var
IO: TIntObj;
SL: TStringList;
Storage:
SL := TStringList.Create(true); // 'OwnsObjects' for recent Delphi versions
IO := TIntObj.Create(123);
SL.AddObjects(IO);
Retrieval:
IO := TIntObj(SL.Objects[4]);
ShowMessage('Integer value: '+ IntToStr(IO.I));
For Delphi-7
TIntObj := TStringList.Create;
and you have to free the objects yourself:
for i := 0 to Sl.Count-1 do
begin
IO := TIntObj(SL.Objects[i]);
IO.Free;
end;
SL.Free;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With