我想创建一个包含整数列表作为其序列化属性之一的组件。我知道我不能将TList<integer>
声明为已发布的属性,因为它不会从TPersistent下降。我已经读过你可以定义“假”发布的属性,如果你重写DefineProperties,但我不太确定它是如何工作的,特别是当它创建一个列表而不是单个值的假属性时。
有人能指出我正确的方向吗?
答案 0 :(得分:5)
这是DefineBinaryProperty
的最小示例(用D2007编写,没有泛型):
type
TTestComponent = class(TComponent)
private
FList: TList;
function GetValueCount: Integer;
function GetValues(Index: Integer): Integer;
procedure ReadValueList(Stream: TStream);
procedure SetValues(Index: Integer; Value: Integer);
procedure WriteValueList(Stream: TStream);
protected
procedure DefineProperties(Filer: TFiler); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function AddValue(Value: Integer): Integer;
procedure ClearValues;
procedure DeleteValue(Index: Integer);
property ValueCount: Integer read GetValueCount;
property Values[Index: Integer]: Integer read GetValues write SetValues;
end;
{ TTestComponent }
function TTestComponent.GetValueCount: Integer;
begin
Result := FList.Count;
end;
function TTestComponent.GetValues(Index: Integer): Integer;
begin
Result := Integer(FList[Index]);
end;
procedure TTestComponent.ReadValueList(Stream: TStream);
var
Count, I, Value: Integer;
begin
ClearValues;
Stream.Read(Count, SizeOf(Count));
for I := 0 to Count - 1 do
begin
Stream.Read(Value, SizeOf(Value));
AddValue(Value);
end;
end;
procedure TTestComponent.SetValues(Index: Integer; Value: Integer);
begin
FList[Index] := Pointer(Value);
end;
procedure TTestComponent.WriteValueList(Stream: TStream);
var
Count, I, Value: Integer;
begin
Count := ValueCount;
Stream.Write(Count, SizeOf(Count));
for I := 0 to Count - 1 do
begin
Value := Values[I];
Stream.Write(Value, SizeOf(Value));
end;
end;
procedure TTestComponent.DefineProperties(Filer: TFiler);
begin
inherited DefineProperties(Filer);
Filer.DefineBinaryProperty('ValueList', ReadValueList, WriteValueList, ValueCount > 0);
end;
constructor TTestComponent.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FList := TList.Create;
// add some values for testing
AddValue(0);
AddValue(1);
AddValue(2);
end;
destructor TTestComponent.Destroy;
begin
FList.Free;
inherited Destroy;
end;
function TTestComponent.AddValue(Value: Integer): Integer;
begin
Result := FList.Add(Pointer(Value));
end;
procedure TTestComponent.ClearValues;
begin
FList.Clear;
end;
procedure TTestComponent.DeleteValue(Index: Integer);
begin
FList.Delete(Index);
end;
和.dfm看起来像这样:
object TestComponent1: TTestComponent
Left = 96
Top = 56
ValueList = {03000000000000000100000002000000}
end
答案 1 :(得分:1)
实现这一目标的最快捷,最简单的方法是使用TCollection - 但是你需要用TCollectionItem类为每个Integer“装饰”付出代价!除非有很多整数,否则这是要走的路,因为你几乎免费获得Object Inspector集成(免费,因为在额外的工作时间内)。
如果您确实希望将列表保存在当前的高效表单(TList)中,那么您是对的,那么就要定义自己的属性。查看Graphics.pas单元,了解如何实现TPicture.DefineProperties,因为这与您的需求非常接近!
想法:如果你去“DefineProperties”路线,你可能想要查看RegisterComponentEditor,因为你的整数列表在Object Inspector中不可见!