gpt4 book ai didi

delphi - 当对象改变时通知TObjectList

转载 作者:行者123 更新时间:2023-12-02 04:28:15 25 4
gpt4 key购买 nike

(TObjectList) 的对象能否知道 (TMyObject) 的某些值何时发生更改?

一些例子:

TMyObject = class
oName: string;
end;

TMyObjectList = class(TObjectList<TMyObject>)
end;

procedure Form1.Button1.Click(Sender: TObject);
var
Obj: TMyObject;
List: TMyObjectList;
Begin
List:= TMyObjectList.Create;
Obj:= TMyObject.Create;
List.Add(Obj);
List[0].oName:= 'Test'; // here a want to know from var (List) when this object (Obj or List[0]) changed his value..
end;

感谢您的帮助。

最佳答案

我刚刚添加了TObservableList<T>类型为 Spring4D(feature/observablelist 分支)。它主要模仿 .NET 并使用 INotifyPropertyChanged 接口(interface)将其事件处理程序附加到支持它的任何对象。该类已经成为 DSharp 的一部分并在生产中使用了相当长的一段时间。它将来可能会发生一些变化并成为库的完整一部分。

这是一个如何使用它的小示例,以便您了解一下:

program Project60;

{$APPTYPE CONSOLE}

uses
Spring,
Spring.Collections,
SysUtils;

type
TNotifyPropertyChangedBase = class(TInterfaceBase, INotifyPropertyChanged)
private
fOnPropertyChanged: Event<TPropertyChangedEvent>;
function GetOnPropertyChanged: IPropertyChangedEvent;
protected
procedure PropertyChanged(const propertyName: string);
end;

TMyObject = class(TNotifyPropertyChangedBase)
private
fName: string;
procedure SetName(const Value: string);
public
property Name: string read fName write SetName;
end;

TMain = class
procedure ListChanged(Sender: TObject; const item: TMyObject;
action: TCollectionChangedAction);
end;

{ TNotifyPropertyChangedBase }

function TNotifyPropertyChangedBase.GetOnPropertyChanged: IPropertyChangedEvent;
begin
Result := fOnPropertyChanged;
end;

procedure TNotifyPropertyChangedBase.PropertyChanged(
const propertyName: string);
begin
fOnPropertyChanged.Invoke(Self,
TPropertyChangedEventArgs.Create(propertyName) as IPropertyChangedEventArgs);
end;

{ TMyObject }

procedure TMyObject.SetName(const Value: string);
begin
fName := Value;
PropertyChanged('Name');
end;

{ TMain }

procedure TMain.ListChanged(Sender: TObject; const item: TMyObject;
action: TCollectionChangedAction);
begin
case action of
caAdded: Writeln('item added ', item.Name);
caRemoved, caExtracted: Writeln('item removed ', item.Name);
caChanged: Writeln('item changed ', item.Name);
end;
end;

var
main: TMain;
list: IList<TMyObject>;
o: TMyObject;
begin
list := TCollections.CreateObservableList<TMyObject>;
list.OnChanged.Add(main.ListChanged);
o := TMyObject.Create;
o.Name := 'o1';
list.Add(o);
o := TMyObject.Create;
o.Name := 'o2';
list.Add(o);
list[1].Name := 'o3';
Readln;
end.

关于delphi - 当对象改变时通知TObjectList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32902798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com