Can I create a constructor that deserializes the string version of my object?

I serialize and deserialize the object (a descendant of TComponent) using the example in the ComponentToString section of the Delphi help file. This means that I can save the object in the VARCHAR field in the database.

When I need to instantiate a new instance of my class from a string stored in the database, can I do this using the form constructor CreateFromString(AOwner: TComponent; AData: String)? Or do I need to use a non-class method that returns an instance of a component's class?

If I can use the designer version, how can I "match" the ReadComponent return value to the "i" that the constructor creates?

Here is an example of deserialization from the help file:

function StringToComponentProc(Value: string): TComponent;
var
  StrStream:TStringStream;
  BinStream: TMemoryStream;
begin
  StrStream := TStringStream.Create(Value);
  try
    BinStream := TMemoryStream.Create;
    try
      ObjectTextToBinary(StrStream, BinStream);
      BinStream.Seek(0, soFromBeginning);
      Result:= BinStream.ReadComponent(nil);
    finally
      BinStream.Free;
    end;
  finally
    StrStream.Free;
  end;
end;
+5
3

, , . Integer. StrToInt .

, , - , , , , . : ", . - ".

, , . , TStream.ReadComponent . , . :

constructor TLarryComponent.CreateFromString(const AData: string);
var
  StrStream, BinStream: TStream;
begin
  Create(nil);
  StrStream := TStringStream.Create(AData);
  try
    BinStream := TMemoryStream.Create;
    try
      ObjectTextToBinary(StrStream, BinStream);
      BinStream.Position := 0;
      BinStream.ReadComponent(Self);
    finally
      BinStream.Free;
    end;
  finally
    StrStream.Free;
  end;
end;

, Self, ReadComponent. , , , .

+6

class function constructor:

type
  TYourClass = class(TComponent)
  public
    class function CreateFromString(AOwner: TComponent; AData: String): TYourClass; static;
  end;

implementation

class function TYourClass.CreateFromString(AOwner: TComponent; AData: String): TYourClass;
begin
   Result := (StringToComponentProc(AData) as TYourClass);
   if AOwner <> nil then
     AOwner.InsertComponent(Result);
end;

AOwner , , TStream.ReadComponent .

:

, Delphi TStream?

: , .

, Name .

+3

class () , constructor.
Delphis , , ( / ).

If you see the source TStream.ReadComponent, you will find that the real class of components is first read from the source stream, then an empty instance is created and RTTI is populated from the stream and returned as the result, This means:

To use TStream.ReadComponent, you need to register your class in the Delphis streaming system through RegisterClass.

+3
source

All Articles