How to assign all property values of one class to another instance of the same class (Views: 100)


How can I assign all property values (or if it’s not possible only published property values, or some of them) of one class (TComponent) to another instance of the same class? What I want to do is:

MyComponent1. {property1} := MyComponent2. {property1};
MyComponent2. {propertyN} := MyComponent2. {propertyN};

Is there a better and shorter way to do this? I tried this: MyComponent1 := MyComponent2; But it doesn’t work. Why not? Can I point to the second component ?


Solve 1:

MyComponent2 and MyComponent1 are pointers to your components, and this kind of assigment leads to MyComponent1 pointing to MyComponent2. But it will not copy its property values.

A better way is to override the assign method of your control, do all property assignment there and call it when you need to copy component attributes. Here's example:

procedure TMyComponent.Assign(Source: TPersistent);
  if Source is TMyComponent then
    property1 := TMyComponent(Source).property1;
    { ... }
    inherited Assign(Source);

To assign properties you'll need to set this line in the code:


Solve 2:

procedure EqualClassProperties(AClass1, AClass2: TObject);
  PropList: PPropList;
  ClassTypeInfo: PTypeInfo;
  ClassTypeData: PTypeData;
  i: integer;
  NumProps: Integer;
  APersistent: TPersistent;
  if AClass1.ClassInfo <> AClass2.ClassInfo then
  ClassTypeInfo := AClass1.ClassInfo;
  ClassTypeData := GetTypeData(ClassTypeInfo);
  if ClassTypeData.PropCount <> 0 then
    GetMem(PropList, SizeOf(PPropInfo) * ClassTypeData.PropCount);
      GetPropInfos(AClass1.ClassInfo, PropList);
      for i := 0 to ClassTypeData.PropCount - 1 do
        if not (PropList[i]^.PropType^.Kind = tkMethod) then
          {if Class1,2 is TControl/TWinControl on same form, its names must be unique}
          if PropList[i]^.Name <> 'Name' then
            if (PropList[i]^.PropType^.Kind = tkClass) then
              APersistent := TPersistent(GetObjectProp(AClass1, PropList[i]^.Name,
              if APersistent <> nil then
                  PropList[i]^.Name, TPersistent)))
              SetPropValue(AClass1, PropList[i]^.Name, GetPropValue(AClass2,
      FreeMem(PropList, SizeOf(PPropInfo) * ClassTypeData.PropCount);

Note that this code skips object properties inherited other than TPersistent.

<< Back to main page