如何在TObject属性中存储Integer,然后向用户显示该值?

时间:2013-04-23 00:36:23

标签: delphi delphi-7

当然,这段代码不会编译。首先,我需要将一个TObject值转换为Integer。然后,将其作为字符串读取。我应该使用什么功能?

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]);

或者也许首先可以使用String而不是Integer?

4 个答案:

答案 0 :(得分:10)

cmbLanguage.Items.AddObject(Format('Item %d', [i]), TObject(i));

在这里,您要添加一个带有"对象的项目"这实际上是一个整数(i)投放到TObject

由于实际上是在对象字段中存储了一个int,所以可以将它转换回Integer,然后将其转换为字符串:

ShowMessage(IntToStr(Integer(cmbLanguage.Items.Objects[cmbLanguage.ItemIndex])));

请注意,您实际上并没有转换任何内容,您只是假装您的整数是TObject,因此编译器不会抱怨。

答案 1 :(得分:2)

如果你知道你将在你的余生中使用Delphi-7坚持使用TObject(i)演员。否则,开始使用适当的对象,这将在升级到64位时节省您的麻烦。

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.

用法:

var
  IO: TIntObj;
  SL: TStringList;

存储:

SL := TStringList.Create(true); // 'OwnsObjects' for recent Delphi versions
IO := TIntObj.Create(123);  
SL.AddObjects(IO);

检索:

IO := TIntObj(SL.Objects[4]);
ShowMessage('Integer value: '+ IntToStr(IO.I));

对于Delphi-7

TIntObj := TStringList.Create;

你必须自己释放这些物品:

for i := 0 to Sl.Count-1 do 
begin
  IO := TIntObj(SL.Objects[i]);
  IO.Free;
end;
SL.Free;

答案 2 :(得分:2)

如果使用 delphi xe或更高,我会使用基于@Jerry答案的泛型类。

的制备:将

unit CoreClasses;

interface

type
  IPrimitiveBox<T> = interface

    procedure setValue(value : T);
    function getValue(): T;

  end;

  TPrimitiveBox<T> = class(TInterfacedObject, IPrimitiveBox<T>)

    private
      value : T;

    public
      constructor create(value : T);

      // IPrimtiveBox<T>
      procedure setValue(value : T);
      function getValue(): T;

  end;

implementation

{ TPrimitiveBox<T> }

constructor TPrimitiveBox<T>.create(value: T);
begin
  self.value := value;
end;

function TPrimitiveBox<T>.getValue: T;
begin
  Result := value;
end;

procedure TPrimitiveBox<T>.setValue(value: T);
begin
  self.value := value;
end;

用法(基于@Jerry示例)

var
  io: IPrimitive<Integer>;

sl := TStringList.create(true);
io := TPrimitive<Integer>.create(123);
sl.addObjects(io)


io := IPrimitive<Integer>(sl.objects[4]);
ShowMessage('Integer value: '+ IntToStr(io.getValue()));

答案 3 :(得分:1)

您不能简单地将对象转换为字符串。这是你必须自己使用你选择的方法,取决于它背后的原因。例如,您可以以XML格式连接表示对象中数据的字符串。但是,Delphi绝对无法为您连接这些数据。


正如其他人所指出的那样,你实际上是在尝试施放 TObject作为Integer。这意味着如果您在TObject字段中存储了一个整数,那么您需要强制转换,例如Integer(MyIntObject)

相关问题