Saving a TObject to a File

前端 未结 7 1498
无人及你
无人及你 2021-02-04 12:45

How can one save an Object, in its current state, to a file? So that it can immediately be read and restored with all its variables.

7条回答
  •  遇见更好的自我
    2021-02-04 13:28

    If you descend your object from TComponent, you can use some built-in functionality to stream the object to a file. I think this only works well for simple objects.

    Some sample code to get you started:

    unit Unit1;
    
    interface
    
    uses
      Classes;
    
    type
      TMyClass = class(TComponent)
      private
        FMyInteger: integer;
        FMyBool: boolean;
        FMyString: string;
      public
        procedure ToFile(AFileName: string);
      published
        property MyInteger: integer read FMyInteger write FMyInteger;
        property MyString: string read FMyString write FMyString;
        property MyBool: boolean read FMyBool write FMyBool;
      end;
    
    implementation
    
    { TMyClass }
    
    procedure TMyClass.ToFile(AFileName: string);
    var
      MyStream: TFileStream;
    begin
      MyStream := TFileStream.Create(AFileName);
      try
        Mystream.WriteComponent(Self);
      finally
        MyStream.Free;
      end;
    end;
    
    end.
    

提交回复
热议问题