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

本文通过一个Delphi代码示例介绍了如何使用TDictionary类的OnKeyNotify和OnValueNotify事件来监听字典中键值的变化,并展示了具体的实现过程。
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://my.oschina.net/hermer/blog/319294

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值