二十八、详测 Generics Collections TDictionary(4): OnKeyNotify、OnValueNotify

本文介绍了一个使用Delphi实现的字典数据结构监听示例。通过定义特定的监听方法,可以实现在添加、删除或提取键值对时触发相应的通知事件。这有助于开发者实时了解字典内部状态的变化。
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Generics.Collections;

type
  TForm1 
= class(TForm)
    Button1: TButton;
    
procedure Button1Click(Sender: TObject);
  
private
    
procedure KeyNotify(Sender: TObject; const Item: string;
      Action: TCollectionNotification);
    
procedure ValueNotify(Sender: TObject; const Item: Integer;
      Action: TCollectionNotification);
  
end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.KeyNotify(Sender: TObject; const Item: string;
  Action: TCollectionNotification);
begin
  
case Action of
    cnAdded     : ShowMessageFmt(
'Key_Add: %s', [Item]);
    cnRemoved   : ShowMessageFmt(
'Key_Remove: %s', [Item]);
    cnExtracted : ShowMessageFmt(
'Key_Extract: %s', [Item]);
  
end;
end;

procedure TForm1.ValueNotify(Sender: TObject; const Item: Integer;
  Action: TCollectionNotification);
begin
  
case Action of
    cnAdded     : ShowMessageFmt(
'Value_Add: %d', [Item]);
    cnRemoved   : ShowMessageFmt(
'Value_Remove: %d', [Item]);
    cnExtracted : ShowMessageFmt(
'Value_Extract: %d', [Item]);
  
end;
end;  

procedure TForm1.Button1Click(Sender: TObject);
var
  Dictionary: TDictionary
<string,Integer>;
begin
  Dictionary :
= TDictionary<string,Integer>.Create();
  Dictionary.OnKeyNotify :
= KeyNotify;
  Dictionary.OnValueNotify :
= ValueNotify;

  Dictionary.Add(
'n1'111); {Key_Add: n1;  Value_Add: 111}
  Dictionary.Add(
'n2'222); {Key_Add: n2;  Value_Add: 222}

  Dictionary.AddOrSetValue(
'n1'123); {Value_Remove: 111;  Value_Add: 123}

  Dictionary.Remove(
'n1');      {Key_Remove: n1;  Value_Remove: 111}

  Dictionary.ExtractPair(
'n2'); {Key_Extract: n2;  Value_Extract: 222}

  Dictionary.OnKeyNotify :
= nil;
  Dictionary.OnValueNotify :
= nil;
  
  Dictionary.Free;
end;

end.

转载于:https://www.cnblogs.com/jxgxy/archive/2009/11/11/1600936.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值