二十六、详测 Generics Collections TDictionary(2): ContainsKey、ContainsValue、AddOrSetValue、TryGetValue...

本文介绍了一个简单的Delphi程序,演示了如何使用TDictionary类进行键值对的添加、查询及更新等基本操作。通过实例展示了如何判断键或值是否存在,如何使用AddOrSetValue方法更新值,以及如何尝试获取值。
unit Unit1;

interface

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

type
  TForm1 
= class(TForm)
    Button1: TButton;
    
procedure Button1Click(Sender: TObject);
  
end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses Generics.Collections;

procedure TForm1.Button1Click(Sender: TObject);
var
  Dictionary: TDictionary
<string,Integer>;
  b: Boolean;
  T: Integer;
begin
  Dictionary :
= TDictionary<string,Integer>.Create();

  
{添加}
  Dictionary.Add(
'n1'111);
  Dictionary.Add(
'n2'222);
  Dictionary.Add(
'n3'333);

  
{判断指定的 Key 是否存在}
  b :
= Dictionary.ContainsKey('n1');
  ShowMessage(BoolToStr(b, True));   
{True}
  b :
= Dictionary.ContainsKey('n4');
  ShowMessage(BoolToStr(b, True));   
{False}

  
{判断指定的 Value 是否存在}
  b :
= Dictionary.ContainsValue(111);
  ShowMessage(BoolToStr(b, True));   
{True}
  b :
= Dictionary.ContainsValue(999);
  ShowMessage(BoolToStr(b, True));   
{False}

  
{使用 AddOrSetValue 时, 如果 Key 存在则替换值; 此时如果用 Add 将发生异常}
  Dictionary.AddOrSetValue(
'n1'123);
  ShowMessage(IntToStr(Dictionary[
'n1'])); {123}

  
{使用 AddOrSetValue 时, 如果 Key 不存在则同 Add}
  Dictionary.AddOrSetValue(
'n4'444);
  ShowMessage(IntToStr(Dictionary[
'n4'])); {444}

  
{尝试取值}
  
if Dictionary.TryGetValue('n2', T) then
    ShowMessage(IntToStr(T)); 
{222}
  
  Dictionary.Free;
end;

end.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值